I am trying to implement multiple requests to database and then display the results in my gatsby app.
I have a working solution with one (!) request.
const ListRezept = (props) => {
const url_id = props.params.id;
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
setTimeout(() => {
fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id)
.then(res => {
if (!res.ok) { // error coming back from server
console.log("error");
throw Error('Could not fetch the data for that resource!');
}
return res.json();
})
.then(data => {
setIsPending(false);
setData(data.value);
setError(null);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('fetch aborted')
} else {
// auto catches network / connection error
setIsPending(false);
setError(err.message);
}
});
}, []);
// abort the fetch
return () => abortCont.abort();
}, [])
...
}
Now I want to integrate the Promise.all function for calling multiple requests. How can I do that? In many websites there is only an example how to call mutiple requests and log them in the console. for e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
In my approach I have to map each result of the single request to an variable.
Here you can see how I started, but failed... I don't know how to handle the multiple answers in Promise.all
const rezeptreq = fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id);
const rezeptartreq = fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezeptart');
Promise.all([rezeptreq, rezeptartreq])
.then(([res1, res2 ]) => {
if (!res1.ok) { // error coming back from server
console.log("error");
throw Error('Could not fetch the data for that resource!');
}
return res.json(), res2.json();
...
Do I have to create an array? How to access the single results of each request?