Home > Back-end >  how to put state array equal to another array using use State
how to put state array equal to another array using use State

Time:02-20

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
    }
  }

CodePudding user response:

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

useEffect(() => {
  if(!productLoading){
    setNewProducts([...newProducts , products]);
    console.log('Products => ' , newProducts)
  }
}, [productLoading])
  • Related