Vincent Law
Vincent Law

Reputation: 95

Dispatch not changing redux state

I am fairly new to redux, and I am running into a problem.

I am trying to implement flash messages to my login page, but redux's dispatch is not changing the UI State.

I want a flash message to appear on the login page after user successfully register.

//login.js

class Login extends Component{
    renderMessage() {
        if (this.props.flashMessageType== "registrationComplete"){
            return (
                <Message
                    style={{textAlign: "left"}}
                    success
                    icon="check circle"
                    header="Account Registration was Successful"
                    list={["You must verify your email before logging in"]}
                />
            );
        } else {
            return (null);
        }
    }

    render() {
        return ({
            this.renderMessage()
        });
    }
}


function mapStateToProps(state) {
    return {
        flashMessageType:state.flashMessage.flashType,
    };
}


export default connect(mapStateToProps, actions)(Login);

Here is the reducer

const initialState = {
    flashType: "",
};

export default function(state = {initialState}, action){
    switch(action.type){
        case USER_REGISTER:
            return [
                ...state,
                {
                    flashType:"registrationComplete"
                }
            ];
        default:
            return initialState;
    }
}

and here is the actions

export const submitForm = (values,history) => async dispatch => {
    const res = await axios.post('/api/signup', values);
    history.push('/');
    dispatch({type: FETCH_USER, payload: res.data});
    dispatch({type: USER_REGISTER});
};

I appreciate your help.

Thanks,

Vincent

Upvotes: 4

Views: 6770

Answers (2)

Matt Carlotta
Matt Carlotta

Reputation: 19762

As Amr Aly mentioned (and now soroush), you're essentially mutating the state when you do:

return[ ...state, { flashType:"registrationComplete" }]

What you really want is:

return { ...state, flashMessage: "registrationComplete" }

Also, some of your code is a bit redundant and/or missing some important instructions (like try/catch blocks).

What your code should look like:

FlashMessage.js

import React, { PureComponent } from 'react';
import Message from '../some/other/directory';
import actions from '../some/oter/directory':

class Login extends PureComponent {
  render = () => (
    this.props.flashMessage == "registrationComplete"
     ? <Message
         style={{textAlign: "left"}}
         success
         icon="check circle"
         header="Account Registration was Successful"
         list={["You must verify your email before logging in"]}
       />
     : null
  )
}    

export default connect(state => ({ flashMessage: state.auth.flashMessage }), actions)(Login)

reducers.js

import { routerReducer as routing } from 'react-router-redux';
import { combineReducers } from 'redux';
import { FETCH_USER, USER_REGISTER } from '../actions/types';

const authReducer = (state={}, ({ type, payload }) => {
  switch(type){
    case FETCH_USER: return { ...state, loggedinUser: payload };
    case USER_REGISTER: return { ...state, flashMessage: "registrationComplete" }
    default: return state;
  }
}

export default = combineReducers({
  auth: authReducer,
  routing
});

actions.js

import { FETCH_USER, USER_REGISTER } from './types';

export const submitForm = (values,history) => async dispatch => {
  try {
    const {data} = await axios.post('/api/signup',values);
    dispatch({ type:FETCH_USER, payload: data });
    dispatch({ type:USER_REGISTER });
    history.push('/');
  catch (err) {
    console.error("Error: ", err.toString());
  }
};

Upvotes: 2

Soroush Chehresa
Soroush Chehresa

Reputation: 5678

Your reducer should be:

const initialState = {
    flashType: "",
};

export default function(state = initialState, action){
    switch(action.type){
        case USER_REGISTER:
            return {
                ...state,
                flashType: "registrationComplete",
            };
        default:
            return state;
    }
}

Upvotes: 2

Related Questions