1

I'm retrieving data from api and storing it in a sharedState. When i'm trying to access this data like below it seems to return the correct. There is one object in the dashboard array with name field.

console.log(newState.profile)

returns:

enter image description here

However when i access dashboards

console.log(newState.profile.dashboards)

it returns

[]

function to set the state from main.js

export function getProfile(state, user) {
    const newState = Object.assign({}, state);

    if (user) {
        db().collection("users").doc(user.uid)
            .onSnapshot((doc) => {
                var data = doc.data()

                if (data) {
                    newState.profile.apps = data.apps
                    newState.profile.dashboards = data.dashboards
                } else {
                    authservice.setUserAcc(user.uid)
                }

            });
    }
    return newState
}

i'm not sure wether this is a javascript behaviour or related to the way i did set up the state.

Peter Pik
  • 11,023
  • 19
  • 84
  • 142
  • 4
    it may be asynchrony at work ... because in the console, what you see is the current state, rather than the state at the time you console.log ... the fact that at the top it says the array is 0 length kind of proves my point - somewhere in your *code* you are pushing to `newState.profile.dashboards` in some asynchronous callback – Jaromanda X Jul 24 '19 at 08:31
  • can you add the code where you make the request and, in context, where you try to log the result. – Thomas Jul 24 '19 at 08:35
  • yes but i'm calling it inside a `stateChanged` method which should observe and call everytime the state has changed. – Peter Pik Jul 24 '19 at 08:36
  • @Thomas i've added the function now, let me know if u need more information to where it is being called – Peter Pik Jul 24 '19 at 08:38
  • 2
    Possible duplicate of [Console.log showing only the updated version of the object printed](https://stackoverflow.com/questions/17320181/console-log-showing-only-the-updated-version-of-the-object-printed) or [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321) – adiga Jul 24 '19 at 08:55
  • Thats pretty much the worst case that happened there ;) youve returned newState without awaiting onSnapshot, so the new state is empty. But once the callback fired you've now mutated the current state. Instead getProfile should wrap the whole body with return new Promise( resolve => { ... where inside onSnapshot, after manipulating new state youd call resolve(newState). This way you have an async action which resolves once the callback is fired and the state propagation is delayed until that happens. – zewa666 Aug 23 '19 at 19:25

0 Answers0