Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

reactjs - Why do I get undefined value from async function?

I have been using Google firestore as a database for my projet. In the collection "paths", I store all the paths I have in my app, which are composed of 2 fields : name, and coordinates (which is an array of objects with coordinates of points).

Anyway, i created a utility file in utils/firebase.js

In the file, i have this function which gets all the paths in my collection and return an array of all documents found :

export const fetchPaths = () => {
    let pathsRef = db.collection('paths');
  let pathsArray = []
    pathsRef.get().then((response) => {
        response.docs.forEach(path => {
      const {nom, coordonnees } = path.data();
      pathsArray.push({ nom: nom, coordonnees: coordonnees})
    })
    console.log(pathsArray)
    return pathsArray;
    });
};

In my react component, What i want to do is to load this function in useEffect to have all the data, and then display them. Here is the code I use :

import { addPath, fetchPaths } from './Utils/firebase';

//rest of the code

useEffect(() => {
        let paths = fetchPaths()
        setLoadedPaths(paths);
    }, [loadedPaths])

//.......

The issue here is if I console log pathsArray in the function it's correct, but it never gets to the state. When i console log paths in the component file, i get undefined.

I am quite new with react, i tried different things with await/async, etc. But I don't know what i am doing wrong here / what i misunderstand.

I know that because of my dependency, i would be supposed to have an infinite loop, but it's not even happening

Thank you for your help

Have a nice day

question from:https://stackoverflow.com/questions/66061995/why-do-i-get-undefined-value-from-async-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

fetchPaths does not return any result. It should be:

export const fetchPaths = () => {
    let pathsRef = db.collection('paths');
  let pathsArray = []
    return pathsRef.get().then((response) => {
        response.docs.forEach(path => {
      const {nom, coordonnees } = path.data();
      pathsArray.push({ nom: nom, coordonnees: coordonnees})
    })
    console.log(pathsArray)
    return pathsArray;
    });
};

note the return statement.

Since the fetchPaths returns a promise, in the effect it should be like following:

useEffect(() => {
     fetchPaths().then(paths => 
        setLoadedPaths(paths));
    }, [loadedPaths])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...