Kevin Hobert
Kevin Hobert

Reputation: 71

How to Save Redux State First before continuing?

I have a project that uses React-redux and Redux-persist in React Native:

These are the dependencies that I used mainly: "expo": "^32.0.0", "react": "16.5.0", "redux": "^4.0.1", "react-redux": "^5.1.1", "redux-persist": "^5.10.0"

I want to make redux stores the data first, then navigate the screen to another navigator. So I was trying using async function and turns out it does not work. But if I dont use async function, it works totally fine, BUT without the navigation.

Why use async then? Because before Redux saved my user information from server, the screen already moved to another navigator, and redux didn't managed to save the user information

This is how I called the redux actions in my LoginScreen:

.then((responseJson) => {
        console.log("Server Response: ", responseJson.data)

        this.storeUserInformation(responseJson.data).then(() => {
          this.toggleLoading()
          this.props.navigation.navigate('AppNavigator')
        })   
    })

storeUserInformation = async (userInformation) => {
  await this.props.saveUserInformation(userInformation)
}
const INITIAL_STATE = {
  userAccountInformation: {},
  userExpoToken: {},
}

const reducer = (state = INITIAL_STATE, action) => {

  switch(action.type){
    case USER_LOGIN:
      console.log("UserAccountReducer", "calling USER_LOGIN")
      return { userAccountInformation: action.payload.members }
    case SAVE_USER_INFORMATION:
      console.log("UserAccountReducer", "calling SAVE_USER_INFORMATION")
      return { userAccountInformation: action.payload }
    case USER_LOGOUT:
      console.log("UserAccountReducer", "calling USER_LOGOUT")
      return {state : {}}
    case SAVE_EXPO_TOKEN:
      console.log("UserAccountReducer", "calling SAVE_EXPO_TOKEN")
      return { userExpoToken: action.payload }
    default:
    console.log("UserAccountReducer", "no Action Called")
      return state
  }
}

export default reducer

Without the async thingy, my action can save the information from server to the redux store. But because after I called this.props.navigate, the action hasn't finished the saving process, and it moves to another page before it finishes

I would like to make the redux SAVE the data from server first, then after it saves the data, it navigates to the next screen

Upvotes: 0

Views: 844

Answers (1)

Jaydeep Galani
Jaydeep Galani

Reputation: 4961

In your reducer make one initial state say isDataLoaded set it default false.

set value of isDataLoaded to true in your appropriate case of reducer when data arrives from API.

Then in your componentWillReceiveProps or componentDidUpdate check it in if condition

if(this.props.isDataLoaded){
   // your data is stored now you can do here navigate things
}

dont forget to map state to props for this state isDataLoaded

Upvotes: 1

Related Questions