Home > other >  useEffect to populate an array
useEffect to populate an array

Time:09-27

I have an empty array that I want to populate by looping through an object, fetching data from a url using each looped items id, and add the retrieved data to the end of the array.

The use case is I am using the Woocommerce Rest API to create a product page. This product has 3 variants of size that i need to add to a dropdown selector. When the parent product displays it's data, it only provides the product ID for each of the variants, not the price as well, which is what I need.

So far I have the following:

const [options, setOptions] = useState();
useEffect(() => {
  product.variations.map((e) => {
    fetch(`${state.source.api}wc/store/products/${e.id}`)
      .then((response) => response.json())
      .then((data) => {
        setOptions(data);
      });
  });
}, []);
console.log("options", options);

I am able to console.log each variant correctly, but have not been able to figure out how to make each variants returned data object be added to an array.

CodePudding user response:

You'll need to fetch all variations, and only then set options.

const [options, setOptions] = useState();
useEffect(() => {
  Promise.all(
    product.variations.map(({ id }) =>
      fetch(`${state.source.api}wc/store/products/${id}`).then((response) => response.json()),
    ),
  ).then(setOptions);
}, []);
console.log("options", options);

(The above formulation is being clever (a bit too clever maybe) with the fact that Promise.all() returns an array we can directly splat into place.)

  • Related