gman_donster
gman_donster

Reputation: 331

assist with fetch function in reactjs

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

Upvotes: 0

Views: 63

Answers (2)

Darwin Island
Darwin Island

Reputation: 481

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 */);
}

Upvotes: 1

MisieQQQ
MisieQQQ

Reputation: 256

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 }))

Upvotes: 1

Related Questions