Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect to populate an array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading