0

I am using useState hook to store an array and initially I am setting it to an empty array. when data is fetched. I am using setState to change it but its not working. thanks in advance

const ShipmentArrival = ({
  isAuthenticated,
  productLoading,
  user,
  products,
  loadProducts,
}) => {
  useEffect(() => {
    loadProducts();
  }, [loadProducts]);

  const [newProducts, setNewProducts] = useState([]);

  if (!productLoading) {
    setNewProducts(products);
    console.log(products);
    for (let i = 0; i < products.length; i++) {
      console.log(newProducts);
      // this log shows that the array is empty
    }
  }

1 Answer 1

1

Actually it is better to handle this kind of senarios in useEffect:

useEffect(() => {
  if(!productLoading){
    setNewProducts([...newProducts , products]);
    console.log('Products => ' , newProducts)
  }
}, [productLoading])
Sign up to request clarification or add additional context in comments.

11 Comments

still not working, array is empty!!
change the dependency inside useEffect to products and also check if products.length > 0 => if(products.length > 0){ ...before code }
and also console.log the products inside useEffect to make sure if products change.
tried both of those already, still nothing. Even console logged the products to check and it does contains data
No there are no errors but since the newProducts array is empty I cant use It. I tried copying products to a simple array( not state array) that works fine but I need State variable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.