0

Hello: i am trying to do a fetch to an endpoint in a react component. The fetch i have is working (all console logs show it is working). since this a function so i can reuse it - i want to return something from it. i tried returning the response but i dont think i have my return in the right place or something else is wrong. here is the log i am referring to:

console.log(response)

and here is the full code:

   const doFetch = (fetchUri) => {   
        
        fetch(fetchUri)
        .then(async response => {
            const data = await response.json();

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response statusText
                const error = (data && data.message) || response.statusText;
                return Promise.reject(error);
            }
            console.log('running fetch')
            console.log(response)
            
            console.log('showing data from fetch')
            console.log(data)

            return(response)

            // this.setState({ totalReactPackages: data.total })
        })
        .catch(error => {
            this.setState({ errorMessage: error.toString() });
            console.error('There was an error!', error);
        });
     
        
    }; 

So I am hoping someone can help me do that 'return' properly. Thanks! Gerard

gman_donster
  • 331
  • 3
  • 12
  • What exactly do you want `doFetch` to return? – Sam Gomena Aug 16 '22 at 01:15
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jabaa Aug 16 '22 at 01:17

2 Answers2

1

you did returned properly inside fetch but you did not returned fetch itself :)

const doFetch = (fetchUri) => {
  return fetch(fetchUri)
    .then(async response => {
      const data = await response.json();

      // check for error response
      if (!response.ok) {
        // get error message from body or default to response statusText
        const error = (data && data.message) || response.statusText;
        return Promise.reject(error);
      }
      console.log('running fetch')
      console.log(response)

      console.log('showing data from fetch')
      console.log(data)

      return (response)

      // this.setState({ totalReactPackages: data.total })
    })
    .catch(error => {
      this.setState({errorMessage: error.toString()});
      console.error('There was an error!', error);
    });
};

doFetch('randomurl').then(parsedAndPreparedResponse => this.setState({ data: parsedAndPreparedResponse }))
MisieQQQ
  • 226
  • 1
  • 6
1

As Michal pointed out in his answer, you're only returning within the fetch, not from doFetch itself.

But to extend a little

The async/await within the then() is unnecessary since no asynchronous call is being made within it. The callback in then() will be run when the fetch promise is resolved. So either get rid of the async/await or change your code to only use async/await. If you do it could look something like this:

const doFetch = async fetchUri => {
    try {
        const response = await fetch(fetchUri)
        // check for error response
        if (!response.ok) {
            throw new Error({
                status: response.status,
                statusText: response.statusText
            });
        }
        // On successful call
        const data = response.json();
        // Return the data
        return data();
    } catch (error) {
        // Error handling
    }
};

You can call the function like this:

// Using the await keyword
const response = await doFetch(/* your fetchUri */);

// Using .then()
// The callback function in then() will run when the promise from
// doFetch() is resolved
doFetch(/* your fetchUri */).then(res => {
    // Whatever you want to do with the response
});

Remember that in order you use the await keyword you need to be inside an async function.

const anAsyncFunction = async () => {
   const response = await doFetch(/* your fetchUri */);
}
Darwin Island
  • 141
  • 1
  • 3
  • hello Darwin - thanks! - i tried what you posted and it did return something, but it was the 'promise' which does not have the resolved result from the fetch, i have been messing around with it to try and get it to not return until it can return the completed result, but have not been able to do it yet.... – gman_donster Aug 16 '22 at 16:28
  • You can call the function like this: doFetch(/* your fetchUri */).then(res => { // Whatever you want to do with the response }); – Darwin Island Aug 16 '22 at 16:49