1

This is how I am trying to populate two dropdowns in my component using useEffects.

function populate_dropdown_one_data() {
    return axios.get("http://127.0.0.1:5001/dropdownonedata");
}

function populate_dropdown_two_data() {
    return axios.get("http://127.0.0.1:5000/dropdowntwodata");
}

React.useEffect(() => {
    populate_dropdown_one_data()
      .then(result => {
        setDropDownOneData(result.data.data);
      });
  }, []);

React.useEffect(() => {
    populate_dropdown_two_data()
      .then(result => {
        setDropDownTwoData(result.data.data);
      });
  }, []);

This only calls populate_dropdown_one_data when the page loads.

If I combine populate_dropdown_one_data and populate_dropdown_two_data inside one useEffect, it only calls populate_dropdown_two_data.

How do I populate data for both the dropdowns when the page loads?

3
  • You could use promise.all React.useEffect(() => Promise.all([populate_dropdown_one_data, populate_dropdown_one_data]).then(values => setDropDownData(values)) , []) Commented Oct 21, 2019 at 3:07
  • both effects should have been called after initial render. Commented Oct 21, 2019 at 3:11
  • @JosephD.: I added alert in the useEffects. You are right. Both are called but only one makes the call to the server (populate_dropdown_two_data). I think I may have to use async await in useEffects here? Commented Oct 21, 2019 at 3:19

2 Answers 2

1

State update is not batched for asynchronous operations.

You can await for both operations in one effect.

React.useEffect(
  () => {
    const fetchData = async () => {
      const one = await populate_dropdown_one_data();
      const two = await populate_dropdown_two_data();

      setDropDownOneData(one.data.data);
      setDropDownTwoData(two.data.data);
    };

    fetchData();
  },
  []
);

Sign up to request clarification or add additional context in comments.

Comments

0
React.useEffect(() => {
 async function load() {
  const [dropdown1, dropdown2] = await Promise.all([
    populate_dropdown_one_data(),
    populate_dropdown_two_data()
  ])
  setDropDownOneData(dropdown1.data.data);
  setDropDownTwoData(dropdown2.data.data);
 }

 load();
}, [])

1 Comment

this only makes ajax call for populate_dropdown_two_data.

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.