I am getting a response from an API:
{
"data": {
// other stuff
"time_breakup": {
"break_timings": [
{
"break_in_time": "2021-11-18T05:32:35.747Z",
"break_out_time": "2021-11-18T05:32:47.871Z"
},
{
"break_in_time": "2021-11-18T06:21:35.740Z",
"break_out_time": "2021-11-18T06:21:39.909Z"
}
],
},
},
"success": true
}
I am using the below function to get this response:
const [shift, setShift]: any = useState();
const getShiftDetails = useCallback(() => {
ApiFunctions.get('shift/' ID)
.then(async resp => {
if (resp) {
setShift(resp.data); // saving the response in state
// some work
} else {
Alert.alert('Error', resp);
}
})
.catch((err: any) => {
console.log(err);
});
}, []);
useEffect(() => {
getShiftDetails();
}, [getShiftDetails, ID]);
So, I have saved the response in a state shift
. Now I want to map this state to display the time on screen:
<View>
{shift.time_breakup.break_timings.map((item: any, index: any) => {
console.log(item.break_in_time),
<>
<View>
<Text>{item.break_in_time}</Text>
<Text>{item.break_out_time}</Text>
</View>
</>;
})}
</View>
However, I am not able to see <Text>{item.break_in_time}</Text>
on screen; and also, in the console, I am getting an infinite loop of time:
console.log:
2021-11-18T05:32:35.747Z
2021-11-18T06:21:35.740Z
2021-11-18T05:32:35.747Z
2021-11-18T06:21:35.740Z
2021-11-18T05:32:35.747Z
2021-11-18T06:21:35.740Z
2021-11-18T05:32:35.747Z
...
I don't know what I am doing wrong.
CodePudding user response:
- Try adding the
ID
inside thegetShiftDetails
useCallback
dependencies array.
const getShiftDetails = useCallback(() => {...}, [ID])
I believe this is what is causing the infinite loop
- Put the
console.log
before returning the view from the map function:
<View>
{shift.time_breakup.break_timings.map((item: any, index: any) => {
console.log(item.break_in_time);
return (
<View>
<Text>{item.break_in_time}</Text>
<Text>{item.break_out_time}</Text>
</View>
);
})}
</View>
CodePudding user response:
You get infinite loop because on each render your function getShiftDetails gets redefined, React creates a shallow object of it on each render cycle, you can use useCallback to memoize it and Declare ID as dependency array.