Home > Blockchain >  Call Multiple API endpoint in useEffect React
Call Multiple API endpoint in useEffect React

Time:04-12

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

CodePudding user response:

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();
  }, []);

CodePudding user response:

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})}) 
   }, [])
  • Related