skip to Main Content

setProductList below does not seem to be working. The console.logs above it for newProducts and productList are different, so setProductList should change productList and cause the other useEffect to fire, but it doesn’t, the first useEffect does not fire. The two console.logs above setProductList are showing up in the console so I know my code is getting to setProductList.

const [productList, setProductList] = useState(filteredProducts);

  useEffect(() => {
    console.log('updating product list...');
  }, [productList]);

  useEffect(() => {
    const cookieLogin = Cookies.get('login');
    if (cookieLogin === undefined) {
      const newProducts = filteredProducts.filter(filterAssociateOnly);
      console.log(newProducts);
      console.log(productList);
      setProductList(newProducts);
    }
  }, [login]);

2

Answers


  1. React evaluates state changes by checking its shallow equality. Since newProducts is derived from filteredProducts, React may not recognize the change in reference and consequently doesn’t trigger a re-render. To ensure a re-render, create a new array by spreading the array into a new array:

    setProductList([...newProducts]);
    
    Login or Signup to reply.
  2. Mutability Issue: Ensure that you are not mutating the productList state directly. React relies on immutable state updates to trigger re-renders properly. Instead of mutating the state directly, make sure you’re creating a new array with the updated values.

    setProductList([...newProducts]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search