The result of an async function is undefined in JS using AXIOS

Viewed 933

I'm trying to fetch data on my client-side from the server-side which is connected to MongoDB.

I'm using React on the front end and Axios for the HTTP requests.

I have 2 files, one for the API and one is the index.jsx of the app.

I successfully fetched the data from the DB but the result I get on the index.jsx is always undefined.

The API FILE:

export async function  getNotesFromDB(googleId) {
let answer;
await axios
    .get(url + "/note/" + googleId, { withCredentials: true }) //WHEN LOCAL : http://localhost:5000/note/
    .then((notesDB) => {
        answer = notesDB; 
    })
    .catch((error) => {
        //Indicates the client of an error getting the notes from
        console.log(error);
         answer= null;
    })
    .finally( () => {
        return answer;
    });

}

The index.jsx file :

import { getNotesFromDB as getNotesFromAPI } from "../API/Notes.jsx";
async function getNotesFromDB() {
    if (userInfo) {
      let googleId = userInfo.googleId;
      const result = await getNotesFromAPI(googleId);
      console.log(result);
 } else {
      history.push("/");
    }
  };
2 Answers

You are returning nothing from the getNotesFromDB function, you should return the result of the axios call:

export async function  getNotesFromDB(googleId) {
  let answer;
  return await axios
  // Rest of the function body ....

you can just return the promise and handle the error

export function getNotesFromDB(googleId) {
return axios
    .get(url + "/note/" + googleId, { withCredentials: true }) //WHEN LOCAL : http://localhost:5000/note/
    .catch((error) => {
        //Indicates the client of an error getting the notes from
        console.log(error);
         return null
    })
}

or

export const getNotesFromDB = (googleId)  => axios
    .get(url + "/note/" + googleId, { withCredentials: true }) //WHEN LOCAL : http://localhost:5000/note/
    .catch((error) => {
        //Indicates the client of an error getting the notes from
        console.log(error);
         return null
    })

or if you prefer to use async/await

export async function  getNotesFromDB(googleId) {
try{
     const res = await axios.get(url + "/note/" + googleId, { withCredentials: true })
     return res 
   }catch(e){
     console.error(e);
     return null;
   }
}
    
Related