1

I am having issues with calling useEffect for multiple API endpoints. Only one or the other are loaded.

My code:

  const [values, setValues] = useState({
     total: [],
     outstanding: []
    });

 useEffect(() => {
 DataService.dashboard_total_Amount().then((response)=>{ setValues({...values, total: response})})
  ChartService.Outstanding().then((response)=>{setValues({...values, outstanding: response})}) 
   }, [])

hope someone can point out my issue. Thanks

2 Answers 2

2

A better way doing the same thing by doing this you only updating state only once hence it also re-render the component once and this look more cleaner and try to use try-catch

  React.useEffect(() => {
    const fetchDetails = async () => {
      try {
        const resDataService = await DataService.dashboard_total_Amount();
        const resChartService = await ChartService.Outstanding();
        setValues({ outstanding: resChartService, total: resDataService });
      } catch (error) {
        console.log(erro);
      }
    };
    fetchDetails();
  }, []);
Sign up to request clarification or add additional context in comments.

Comments

1

The function inside the useEffect acts as a closure for the values variable. To ensure you update the most current value, you can pass a function to setValues:

  const [values, setValues] = useState({
     total: [],
     outstanding: []
    });

 useEffect(() => {
 DataService.dashboard_total_Amount().then((response)=>{ setValues((values) => {...values, total: response})})
  ChartService.Outstanding().then((response)=>{setValues((values) => {...values, outstanding: response})}) 
   }, [])

Comments

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.