dper
dper

Reputation: 904

Open the application with the last State before closed

I am new to react-native and I am building an app which has an authentication module. The login works with the jwt token and sets the state of the user. I want to save the state of the user such that the next time the user launches the application, it retrieves the last state of the application and skips the login module. Note that I am not talking about the app going to background. I am storing the jwt in the async storage once the login is true in the api function.

Can anyone advise me to correct pointer to look for the same.

Below is my login auth code -

Reducer -

import { combineReducers } from 'redux';

const initialAuthState = { isLoggedIn: false };
const Login = 'Login';
const Logout = 'Logout';
export const login = data => ({
  type: Login,
  data
});

export const logout = () => ({
  type: Logout,
});

function auth(state = initialAuthState, action) {
  switch (action.type) {
    case Login:
      console.log("reducer called for Login");
      console.log(action.data.user)
      return { ...state, isLoggedIn: true, user: action.data.user};
    case Logout:
      console.log("reducer called for logout");
      return { ...state, isLoggedIn: false, user: {} };
    default:
      return state;
  }
}

const AppReducer = combineReducers({
  auth,
});

export default AppReducer;

login.js

import React from 'react';
import { StyleSheet, Text, TextInput, View } from 'react-native';
import Button from 'react-native-button';
import PropTypes from 'prop-types';
import AppStyles from '../AppStyles';
import Api from '../Api';
import { connect } from 'react-redux';
import { login } from '../reducers';

class LoginScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //   loading: true,
      email: 'username',
      password: 'password'
    };
  }

  onPressLogin = () => {

    Api.login(this.state.email, this.state.password, (success, data) => {
      if (success) {
        this.props.login({ user: data.username});
      } else {
        alert(data);
      }
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={[styles.title, styles.leftTitle]}>Sign In</Text>
        <View style={styles.InputContainer}>
          <TextInput
            style={styles.body}
            placeholder="E-mail or phone number"
            onChangeText={text => this.setState({ email: text })}
            value={this.state.email}
            underlineColorAndroid="transparent"
          />
        </View>
        <View style={styles.InputContainer}>
          <TextInput
            style={styles.body}
            secureTextEntry
            placeholder="Password"
            onChangeText={text => this.setState({ password: text })}
            value={this.state.password}
            underlineColorAndroid="transparent"
          />
        </View>
        <Button
          containerStyle={styles.loginContainer}
          style={styles.loginText}
          onPress={() => this.onPressLogin()}
        >
          Log in
        </Button>
      </View>
    );
  }
}

Thanks

Upvotes: 0

Views: 554

Answers (2)

Aneta
Aneta

Reputation: 78

An example how to use redux-persist:

store.js

    // Imports: Dependencies
import AsyncStorage from '@react-native-community/async-storage';
import { createStore, applyMiddleware, compose } from 'redux';
import { createLogger } from 'redux-logger';
import { persistStore, persistReducer } from 'redux-persist';
import rootReducer from '../reducers/index';
import thunk from 'redux-thunk';

// Middleware: Redux Persist Config
const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: [
    'authReducer',
  ],
};

// Middleware: Redux Persist Persisted Reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);

let composeEnhancers = compose;

if(__DEV__) {
  composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
}

// Redux: Store
const store = createStore(
  persistedReducer,
  composeEnhancers(
    applyMiddleware(
      thunk, 
      createLogger()
    )
  )
);

// Middleware: Redux Persist Persister
let persistor = persistStore(store);

export {
  store,
  persistor,
};

Upvotes: 0

Thales Kenne
Thales Kenne

Reputation: 2932

You could you redux-persist. I see you're already managing your state with Redux, it is pretty simple to setup and will persist your reducers through sessions. You could also hold on a Splash Screen while it is loading, so the user interaction is seamless. You'd then check for auth info in the reducer before sending to the Login Screen or Main Screen.

You could also use some kind of local database, such as Realmjs, and then store whatever info you need in there.

Upvotes: 1

Related Questions