Estoy tratando de obtener datos en mi lado del cliente desde el lado del servidor que está conectado a MongoDB.
Estoy usando React en el front-end y Axios para las solicitudes HTTP.
Tengo 2 archivos, uno para la API y otro es el index.jsx de la aplicación.
Obtuve con éxito los datos de la base de datos, pero el resultado que obtengo en index.jsx siempre está indefinido.
El ARCHIVO API:
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; });}
El archivo index.jsx:
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("/"); } };No devuelve nada de la función getNotesFromDB , debe devolver el resultado de la llamada axios:
export async function getNotesFromDB(googleId) { let answer; return await axios // Rest of the function body ....puedes simplemente devolver la promesa y manejar el 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 }) }o
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 })o si prefiere usar 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; } }