React Question about promise in a for loop

Make another component which fetches the data and renders them once the responses have come back. Use Promise.all to wait for all of the Promises to resolve together.

const getName = id => axios
    .post(TARGET_META_URL, {
        filters: [
            {
                field: "id",
                values: [id.key]
            }
        ]
    })
    .then(response => response.data[0].name);
const AsyncDropdown = ({ ids }) => {
    const [options, setOptions] = useState();
    useEffect(() => {
        Promise.all(ids.map(getName))
            .then(setOptions)
            .catch((err) => {
                // handle errors
            });
    }, [ids]);
    return options ? <Dropdown options={options} /> : null;
}

And replace your original render method with:

render() {
  return(
    <SomeOtherComponent>
      <AsyncDropdown ids={ids} />
    </SomeOtherComponent>
  );
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top