React Native Redux - initialize default state from asyncstorage

I am developing an Android application according to which my screen depends on whether the user is logged in or not. Login data is stored inside AsyncStorage.

By the time the application starts, it should receive data from AsyncStorage and make it as the default state. How can i achieve this?

Below is my reduction structure

index.android.js

import {
  AppRegistry,
} from 'react-native';

import Root from './src/scripts/Root.js';

AppRegistry.registerComponent('reduxReactNavigation', () => Root);

Root.js

import React, { Component } from "react";
import { Text, AsyncStorage } from "react-native";
import { Provider, connect } from "react-redux";
import { addNavigationHelpers } from 'react-navigation';

import getStore from "./store";
import { AppNavigator } from './routers';

const navReducer = (state, action) => {
    const newState = AppNavigator.router.getStateForAction(action, state);
    return newState || state;
};

const mapStateToProps = (state) => ({
    nav: state.nav
});

const user = {};

class App extends Component {
  constructor(){
    super();
  }

  render() {
    return (
        <AppNavigator
            navigation={addNavigationHelpers({
                dispatch: this.props.dispatch,
                state: this.props.nav
            })}
        />
    );
  }
}

const AppWithNavigationState = connect(mapStateToProps)(App);

const store = getStore(navReducer);

export default function Root() {
    return (
        <Provider store={store}>
            <AppWithNavigationState />
        </Provider>
    );
}

custom gears

import {
    REGISTER_USER,
    UPDATE_USER,
    LOGIN_USER
} from '../../actions/actionTypes';

import { handleActions } from 'redux-actions';

**// here is the default state, i would like to get from asyncstorage**
const defaultState = {
  isLoggedIn: false,
  user:{},
};

export const user = handleActions({
  REGISTER_USER: {
    next(state, action){
      return { ...state, user: action.payload, isLoggedIn: true }
    }
  },
  LOGIN_USER: {
    next(state, action){
      return { ...state, user: action.payload, isLoggedIn: true }
    }
  },
}, defaultState);
+4
source share
1 answer

You can use the component of the component lifecycle componentWillMount to retrieve data from AsyncStorage and you can change the state when data arrives.

0
source

Source: https://habr.com/ru/post/1679525/


All Articles