2

This question would seem basic but I'm stuck on this. I've got a class which is not a component, I used it to initialize a DB and do DB CRUD operations. The class has a method readMatrix which reads a dictionnary from a DB and returns it as a matrix. I can check the value of the matrix in the console and it is correct. However the value which is returned to the calling function is "undefined" instead of what I'm seeing in the console log. I tried to fix it with Redux/Hooks and found this way too complexe for a novice like me (I'm using functions/hooks as components, but a class for DB management).

Here's the code of the class:

readMatrix (r,c,id) {
    const row = new Array(c).fill(null);
    var tempMatrix=[];
        for (let i=0; i<r; i++){
        tempMatrix.push([...row])
    }

    var restaurantRef = app.database().ref("/restaurants");
    restaurantRef.orderByKey().equalTo("1").on("child_added", function(snapshot){           
        //  console.log(snapshot.child("/layout").val());
        var restaurant=snapshot.child("/layout").val();
        for (const [key, value] of Object.entries(restaurant)) {
              let i=key;
              for (const [rowkey, rowvalue] of Object.entries(value)){
                  let j=rowkey;
                  tempMatrix[i][j]=rowvalue;                      
              }
        }
            console.log(tempMatrix);
    return(tempMatrix); 
        
}); 

}

And here's the calling function:

    useEffect(()=>{
            
    setMatrix(FirebaseClass.readMatrix(matrixHeight,matrixWidth, 1))
    console.log(matrix);    
    
  }, []);

Any idea on what's wrong there ?

  • 1
    The code inside `readMatrix` seems asynchronous. `return tempMatrix` will be executed before any values have been added to `tempMatrix`. You should return a promise instead. Maybe [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) helps. – Felix Kling Dec 17 '20 at 16:46

1 Answers1

0

Thanks for the answer(s)

Here's the only think that fixed it.

  1. Declare readMatrix as async.
  2. Get the value in the matrix the following way:
FirebaseClass.readMatrix(matrixHeight,matrixWidth, 1).then(setMatrix)

Hope the answer is clearer than the question.