how can I return axios data to feed view?

Viewed 73

I am building feed news using reactjs, but however, I notice that Axios is not returning data back to my browser feed in order to process the data, what am I missing on this code?

const browserFeed = async () => {  
    const response = await browse();
    console.log(response)
    setFeed(response.data.results);  // undefined
    setIntialized(true);  
  };


  export const browse = () =>  {
    axios.get('xxxxxxxxxxx').then((result) => {
      return result // undefined
    }).catch((error) => {
      return error;
    })
  }
1 Answers

You are missing returning the Promise axios.get returns.

export const browse = () =>  {
  return axios.get('xxxxxxxxxxx').then((result) => {
    return result;
  }).catch((error) => {
    return error;
  });
};

You can simply return the Promise though, you don't need to chain another .then just to return the resolved value.

export const browse = () =>  {
  return axios.get('xxxxxxxxxxx').catch((error) => {
    return error;
  });
};

And to be honest I don't think you want to catch and return the error here either since your component logic is written to assume success. You can return the Promise and handle any rejected promises in a try/catch.

export const browse = () =>  {
  return axios.get('xxxxxxxxxxx');
};

But this is a little boring, may as well just make the axios call in the component. surround all the fetching logic in a try/catch, set the feed in the happy success branch, set any error state in the sad failure branch, and set the initialized state in finally block so no matter pass/fail you can indicate data was fetched.

const browserFeed = async () => {
  try {
    const response = await axios.get('xxxxxxxxxxx');
    console.log(response)
    setFeed(response.data.results);
  } catch(error) {
    // set any error state
  } finally {
    setInitialized(true);
  }
};

This avoids the mixing of the async/await syntax with any promise-chain syntax, which should be avoided.

Related