0

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?

1 Answer 1

0
    function MultipleRequest() {

    const abortControllerRef = useRef(null);


    useEffect(() => {
        if (!abortControllerRef.current) {
            const newAbortController = new AbortController();
            abortControllerRef.current = newAbortController;
        }

        callMultipleRequest();

        return () => {
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
        };
    }, [])

    const callMultipleRequest = async () => {
        const abortController = abortControllerRef.current;
        const rezeptreq =  fetch('https://dummyjson.com/products/1', { signal: abortController.signal });
        const rezeptartreq =  fetch('https://dummyjson.com/products/1', { signal: abortController.signal });

        Promise.all([rezeptreq, rezeptartreq]).then((responseArray) => {
            responseArray.forEach(element => {
                if (!element.ok) {
                    console.log("error");
                    throw Error('Could not fetch the data for that resource!');
                }
            });
            return Promise.all(responseArray.map(res => res.json()));
        }).then((res) => {
            console.log("res => ", res);
        }).catch((err) => {
            console.error(err);
        })
    }


    return (
        <div>MultipleRequest</div>
    )
}

It makes two HTTP requests to the same endpoint using the fetch API. The requests are made using the AbortController API, which allows the requests to be aborted if needed. The component uses the useEffect hook to initialize the AbortController and call the callMultipleRequest function when the component mounts. The callMultipleRequest function makes the HTTP requests and handles the responses. If any of the responses are not ok, an error is thrown. The responses are then logged to the console. The component returns a element with the text "MultipleRequest".

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! And how to assign the result of each single request to andifferent variable? For e.g. first request assign to data_req1 and second request assign to data_req2... As I mentioned I found many websites to log the results in the console, but I want to access the values of each single request
const [apiResponse, setApiResponse] = useState([]); Promise.all([...]).then((res) => { // make json }).then((res) => { if(res?.length) { const _response = res.reduce((result, cur, i) => { result['data_req'+(i+1)]=cur; return result; },{}) setApiResponse(_response); } }).catch((err) => { //err }) // use apiResponse?.data_req1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.