So I am calling an api and storing the result in a state called shift and getting the following result:
[
{
"id": 123,
"status": "created",
"expected": {
"end_time": "2021-10-01",
"start_time": "2021-10-01"
},
},
{
"id": 567,
"status": "created",
"expected": {
"end_time": "2021-09-30",
"start_time": "2021-09-30"
},
}
]
Now am mapping this shift state in following way:
{shift.map((item: any, key: any) => (
<>
<ShiftComponent
Name={'name'}
StartTime={item.expected.start_time}
EndTime={item.expected.end_time}
Address={'address'}
/>
</>
))}
To get this name and address I have to call another api using the id from first api, so I have extracted the id's from first api in an array:
id = ["123", "567"]
and then calling the second api and storing the result in value state:
for (let i = 0; i < id.length; i++) {
ApiCall.get(Url + 'value/' + id[i])
.then(async (resp) => {
if (resp) {
setValue(resp.data);
} else {
Alert.alert('Error', resp);
}
})
.catch((err: any) => {
console.log(err);
});
}
result of second api:
{
"address": {
"state": "anice state",
"city": "nice city",
},
"name": "Nice name",
"id": "123"
}
{
"address": {
"state": "anice state 2",
"city": "nice city 2",
},
"name": "Nice name 2",
"id": "567"
}
Based on the result of second api, how can I give name and address in my ShiftComponent. I tried mapping over the already mapped shift, but that is creating duplicate and wrong outputs.
P.S.: I have only shown 2 example output in my api's call, in reality there are many more
Please help, I am not able to find the solution for this.!!
If you really need to call your API separately for each id, you might want to either move this call into ShiftComponent or wrap it with another component that will take care of the call. The way you're doing it now contains a flaw:
for (let i = 0; i < id.length; i++) { // <-- this is a loop
ApiCall.get(Url + 'value/' + id[i])
.then(async (resp) => {
if (resp) {
setValue(resp.data); // <-- this will overwrite state with every API response
} else {
Alert.alert('Error', resp);
}
})
.catch((err: any) => {
console.log(err);
});
}
Calling setValue in a loop like this means you only retain the latest response from the API. Again, the simplest solution to this is to make one API call in each child component. It might look something like this:
{shift.map((item: any, key: any) => (
<ShiftComponent // make the API call inside this component
id={item.id}
StartTime={item.expected.start_time}
EndTime={item.expected.end_time}
/>
))}