Home > Back-end >  React - How to combine two api response together
React - How to combine two api response together

Time:09-06

I'm having a problem in combining these two different api responses.

const pastData = useSelector(
    (state) => state.transactions.pastData,
  );
const latestData = useSelector(
    (state) => state.transactions.latestData,
  );

pastData response shape: {loading: false, data: Array(3)}

latestData response shape: {loading: false, data: Array(6)}

I tried to combine them by using this:

const combinedResponse = {...pastData, ...latestData}

But when I logged combinedResponse it didn't work as expected.

Expected output is to merge data from responses just like this {loading: false, data: Array(9)}

CodePudding user response:

const combinedResponse = {loading: pastData[0].loading, data: pastData}
        
latestData.map((element)=> {combinedResponse.data.push(element.data)})

The Initial Values can be changed as you choice. Can be empty [ ] or latestData.

Then, need to push data into combinedResponse's data.

CodePudding user response:

See these simplest approch:

var callOne = useCallback(async()=>{
    //...do call
    //Return response
},[])

var callTwo = useCallback(async()=>{
    //...do call
    //Return response
},[])

const combineData = (r1,r2) => {
   return {isLoading: r1?.isLoading, data: [...r1?.data || [], ...r2?.data || []]}
}

useEffect(()=>{
    var result = await callOne();
    var result2 = await callTwo();
    //COMBINE LOGIC
    combineData(result, result2);
},[])

CodePudding user response:

Hey this is how you can merge both

const pastData = useSelector(
    (state) => state.transactions.pastData,
  );
const latestData = useSelector(
    (state) => state.transactions.latestData,
  );


const pastDataArr = pastData?.data ?? []

const latestDataArr = latestData?.data ?? []

const finalData = [...pastDataArr , ...latestDataArr];

const combinedResponse = {
loading:latestDataArr?.loading,
data:finalData
}

you can now use combinedResponse .

  • Related