Skip to content
Advertisement

GET request with axios (using await) returning undefined

I’m using axios to get data and then handle 401 error and so far it works, but there is a problem when I try to import my axios function and use it I got undefiend but not the actual response. Btw I have seen simillar questions and didn’t find answear.

axios function code

import axios from 'axios';

const stateFetch = async (user, id) => { 
  console.log("in function stateFetch");
  axios.defaults.headers.common = {'Authorization': `bearer ${user.json.token}`}
  await axios.get(`/api/name/blogs/${id}/validate`);
}

axios.interceptors.response.use(response => {
  console.log(response);
  return response;
}, error => {
  console.log(error.response);
if (error.response.status === 401) {
   return "user is not authorized to edit this blog";
}
return error;
});

export default stateFetch;

the fetching part

const fetchState = async () => {
            //chek if client is authenticated to edit the blog
            console.log("fetchState");
            try {
                const response = await stateFetch(user, id);
                console.log(response);
                if (!response.ok) {
                    throw Error(response);
                }
                setState(response);
            } catch (error) {
                console.log(error);
                if (error.message === "user is not authorized to edit this blog")
                {
                    console.log("user is not authorized to edit this blog");
                    setState({state: "false"});
                    return;
                }
                setError(error);
            }
        }

what I get on console picker of console log sory for picture

Advertisement

Answer

As you do not have explicit return from async function, stateFetch returns undefined

const stateFetch = async (user, id) => { 
  console.log("in function stateFetch");
  axios.defaults.headers.common = {'Authorization': `bearer ${user.json.token}`}
  await axios.get(`/api/name/blogs/${id}/validate`);
  // return undefined
}

just add return

const stateFetch = async (user, id) => { 
  console.log("in function stateFetch");
  axios.defaults.headers.common = {'Authorization': `bearer ${user.json.token}`}
  return await axios.get(`/api/name/blogs/${id}/validate`);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement