Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate the initialState in Redux from react native's AsyncStorage?

I have a React Native app. I am storing username and uid in AsyncStorage so they don't have to log in every time. How do I populate the initialState with these values. There are some packages that do it for you but it seems like this should be doable without the overhead of another package. Right now initial state is just empty values.

const initialState = {
  uid: "",
  username: "",
};
like image 385
Steve Carey Avatar asked Oct 31 '18 00:10

Steve Carey


1 Answers

Here is the solution I came up with. Just create an action that gets the AsyncStorage properties and dispatch the array of properties to the reducer where they are assigned to the state. And you call the action directly on the store. Much lighter than adding a whole other library. For simplicity I'll assume all the Redux code is in one file called myRedux.js:

// Imports:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { AsyncStorage, } from "react-native";

// Set initial state to empty values:
const initialState = {
  uid: "",
  username: "",
};

// Reducer: 
const reducer = (state = initialState, action) => {
  switch(action.type) {
    case "setInit":
      return { 
        ...state, 
        uid: action.uid,
        username: action.username,
      }

    default: 
      return state;
  }
};

// Store
const store = createStore(reducer, applyMiddleware(thunk));
export { store };

// Action
const setInit = (result) => {
  return {
    type: "setInit",
    uid: result[0][1],
    username: result[1][1],
  };
} 

const getAsyncStorage = () => {
  return (dispatch) => {
    AsyncStorage.multiGet(['uid', 'username'])
    .then((result) => {dispatch(setInit(result))});
  };
};

// Dispatch the getAsyncStorage() action directly on the store.
store.dispatch(getAsyncStorage());

Then in the Screen files you can access them with mapStateToProps:

const mapStateToProps = (state) => {
  return {
    uid: state.uid,
    username: state.username,
  };
}

// Access the prop values in the render:
render() {
  return (
    <View>
      <Text>Uid: {this.props.uid}</Text> 
      <Text>Username: {this.props.username}</Text>
    </View>
  );
}

// Connect mapStateToProps to the component class
export default connect(mapStateToProps)(MyScreen);
like image 86
Steve Carey Avatar answered Oct 24 '22 04:10

Steve Carey