Search code examples
javascriptreactjsreduxreact-reduxredux-thunk

React redux how to use getState()


I am fetching data from the Firebase Real-time database and storing it into my redux state. How can I create an action that will get the latest and most up to date state after the initial call?

const getIds = (state) => state.notes.activeNotes;

export const getUserNotes = (currentUserId) => (dispatch, getState) => {
  getFromFirebase(`/Notes/${currentUserId}/`, (response) => {
    var ids = Object.keys(response)
      dispatch(setNoteIds(ids)); //should dispatch ids something like this [1,2,3,4,5]
  })

  const test= getIds(getState());
  console.log(test); //current output []
}

Expected output: [1,2,3,4,5]
Actual output: []

Solution

  • Assuming the function getFromFirebase returns a promise then you can switch your method to async as following:

    
    export const getUserNotes = (currentUserId) => async (dispatch, getState) => {
      // wait the result dispatched
      await getFromFirebase(`/Notes/${currentUserId}/`, (response) => {
        var ids = Object.keys(response)
          dispatch(setNoteIds(ids)); //should dispatch ids something like this [1,2,3,4,5]
      })
      
      const test= getIds(getState());
    }
    
    

    Or if the getFromFirebase is not a promise, you can wrap it up by a promise:

    export const getUserNotes = (currentUserId) => async (dispatch, getState) => {
      // wrap in a promise
      await new Promise(resolve => {
        getFromFirebase(`/Notes/${currentUserId}/`, (response) => {
          var ids = Object.keys(response)
            dispatch(setNoteIds(ids)); //should dispatch ids something like this [1,2,3,4,5]
            resolve();
        })
      })
      
      const test= getIds(getState())
    }