2

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 2

6

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 ....
Sign up to request clarification or add additional context in comments.

1 Comment

Oh wowI totally missed that I actually didn't return anything. But even after I added the return before the await it continues to return undefined. Although when I used try/catch/finnaly method it worked.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.