0

In Home component I am fetching product details from Product context. But when context value is changing the updated value is not coming in the Home component.

Here is home component:

import React, { useEffect, useState } from "react";
import { useProductList } from "../../context/ProductContext/ProductContext";
import { WishListButton } from "../WishListButton/WishListButton";
import { Filters } from "../Filters/Filters";

const Home = () => {
  const { productList } = useProductList();
  /*let [gameList, setGameList] = useState();

  useState(() => {
    console.log(productList ? productList[0] : null);
    setGameList(productList);
  }, [productList]);*/

  console.log(productList);
  return (
    <div>
      <h1>Home</h1>
      <Filters />
      <div className="products">
        {productList
          ? productList.map((item, i) => (
              <div key={i} className="card">
                <div className="card-name">{item.name}</div>
                <div>
                  <WishListButton id={item._id} />
                </div>
                <div>Rs.{item.price}</div>
              </div>
            ))
          : null}
      </div>
    </div>
  );
};

export { Home };

This is my ProductContext

import { createContext, useContext } from "react";

export const ProductContext = createContext();

export function useProductList() {
  return useContext(ProductContext);
}

2 Answers2

1
const {productList}= useContext(useProductList);

You need to use the useContext hook to get the value

0

Found the issue. I was doing this earlier

const ascPriceState = state.sort((a, b) => (a.price > b.price ? 1 : -1));

Now doing this

state.sort((a, b) => (a.price > b.price ? 1 : -1));
const ascPriceState = [...state];

Needed to return new object.