peter
peter

Reputation: 1582

React-native not rerendering with Redux action

I have a component that should navigate when a user is authenticated:

componentDidUpdate(prevProps, prevState) {
    if (this.props.authenticated) {
      this.props.navigation.navigate('Main')
    }
  }

When I dispatch authLogin it should cause a rerender, which handles the navigation:

export const authLogin = (username, password) => {
  return dispatch => {
    dispatch(authStart());
    axios.post(`http://10.0.2.2:8000/api/v1/rest-auth/login/`, {
      username: username,
      password: password
    })
      .then(response => {
        var token = response.data.key;
        try {
          AsyncStorage.setItem('token', token);
        } catch (err) {
          console.log(err)
        }
        dispatch(authSuccess(token));
      })
      .catch(err => {
        dispatch(authFail());
        console.log(err);
      })
  }
}

Here is my reducer:

export default function (state = initialState, action) {
  switch (action.type) {
    case "AUTH_START": {
      return {
        ...state,
        authenticating: true,
      }
    }
    case "AUTH_SUCCESS": {
      return {
        ...state,
        authenticating: false,
        authenticated: true,
        token: action.token,
      }
    }
    case "AUTH_FAIL": {
      return {
        ...state,
        authenticating: false,
        authenticated: false,
      }
    }
    case "AUTH_LOGOUT": {
      return {
        ...state,
        authenticating: false,
        authenticated: false,
        token: null,
      }
    }
    default:
      return state
  }
}

and action creators:

export const authStart = () => ({type: "AUTH_START"})
export const authSuccess = token => ({type: "AUTH_SUCCESS", token})
export const authFail = () => ({type: "AUTH_FAIL"})

My console is logging that Redux actions are dispatched and that the state is changing, but no rerendering is happening. Here's the whole component:

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import LoginForm from '../components/LoginForm';
import { authLogin } from '../actions/authActions';

export class LoginScreen extends Component {
  handlePress = async (username, password) => {
    await this.props.authLogin(username, password);
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.authenticated) {
      this.props.navigation.navigate('Main')
    }
  }

  render() {
    return (
      <View style={styles.loginForm}>
        <LoginForm handlePress={this.handlePress} {...this.props} />
      </View>
    );
  }
}

const mapState = state => {
  return {
    authenticated: state.auth.authenticated
  }
};

const mapDispatch = dispatch => {
  return bindActionCreators({
    authLogin,
  }, dispatch)
};

export default connect(mapState, mapDispatch)(LoginScreen);

LoginScreen.propTypes = {
  authLogin: PropTypes.func.isRequired,
  authenticated: PropTypes.bool.isRequired,
};

const styles = StyleSheet.create({
  loginForm: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1
  }
});

and here's my store:

import {  combineReducers } from 'redux';
import { createStore, applyMiddleware } from 'redux';
import { logger } from 'redux-logger';
import thunk from 'redux-thunk';
import auth from './auth'

const reducer = combineReducers({auth})
const enhancer = applyMiddleware(thunk, logger)
const store = createStore(reducer, enhancer)

export default store

The store is connected in the Provider in App.js.

Upvotes: 3

Views: 702

Answers (2)

Faisal Arshed
Faisal Arshed

Reputation: 538

Why not put the authentication check and navigation statement inside the handlePress().

handlePress = async (username, password) => {
    await this.props.authLogin(username, password);
    if (this.props.authenticated) {
      this.props.navigation.navigate('Main')
    }
  }

After the authLogin() dispatches the action and state is updated, you can check the authentication status and navigate the user.

Hope this helps!

Upvotes: 0

peter
peter

Reputation: 1582

I added another reducer, which fixed it instantly. Apparently redux didn't like that combineReducers() only had one argument.

i.e. change

const reducer = combineReducers({auth})

to

const reducer = combineReducers({auth, otherReducer})

Upvotes: 3

Related Questions