I'm trying to fetch data from two different api-endpoints and trying to show the whole data in the same page in my React native appThis is the snapshot of the error I'm getting with the code snippet
-
There is nothing that prevents you from doing so. Fetch data from multiple apis then display it. There is a function, literally named fetch, that fetches data, you should look into it.Félix Adriyel Gagnon-Grenier– Félix Adriyel Gagnon-Grenier2020-02-19 21:34:24 +00:00Commented Feb 19, 2020 at 21:34
-
when i'm trying to fetch data from multiple endpoints and set it to two different variables the value of the 2nd variable is always null. Getting a null pointer exception thereSandip Biswas– Sandip Biswas2020-02-19 21:39:26 +00:00Commented Feb 19, 2020 at 21:39
-
Please edit your question with relevant details, the exact error message and what code specifically causes that problem.Félix Adriyel Gagnon-Grenier– Félix Adriyel Gagnon-Grenier2020-02-19 21:40:52 +00:00Commented Feb 19, 2020 at 21:40
Add a comment
|
1 Answer
The same exception was coming for me as well...tried a different approach.Chained one fetch method in another and tried to set the value into all the datasource variables in the first fetch block and then used the 2nd variable in the next fetch block again.
The issue got resolved and the values are now coming as required. Don't know if this is the perfect approach but it solved the issue, please try to refer the below example
fetch(‘endpoint1’, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
//send the parameters you need to use to fetch the data
from endpoint
//e.g. “id”: this.state.id,
…
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource1: responseJson,
dataSource2: responseJson,
})
})
.then(()=>{
fetch(‘endpoint2', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
//send the parameters you need to use to fetch the data
from endpoint
//e.g. “id”: this.state.id,
…
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource2: responseJson,
})
})
})
.catch((error) => {
console.error(error);
});