Raffael Reichelt
Raffael Reichelt

Reputation: 61

react/redux component does not rerender after state change

Am in big trouble, cause I do need to speed-learn react/redux. I have 2 components, one form one output. The form bravely dispatches my actions and I am logging the changes with a subscribe to my console: everythings fine and correctly but the following component does not rerender … any Idea?

import React, {Component} from "react";
import { connect } from "react-redux";

const mapStateToProps = state => {
  return { message: state.message, speaker: state.speaker };
};

class connectedOutput extends Component {
    render(){
        const{message, speaker} = this.props
        return (<p>{speaker}: &nbsp;{message}</p>)
    }
}

const Output = connect(mapStateToProps)(connectedOutput);
export default Output;

This is my reducer:

import { MESSAGE } from "../constants/action-types";
import { SPEAKER } from "../constants/action-types";
const initialState = {message:'Something', speaker:'Scotty'}

const basicReducer = (state = initialState, action) => {

    let speaker = state.speaker == 'Scotty' ? 'Bones' : 'Scotty';
    switch(action.type){
        case MESSAGE:
            Object.assign(state, action.message)
                return state;
            case SPEAKER:
                Object.assign(state, {speaker});
                return state;
            default:    
                return state;
        }
    };

    export default basicReducer;

The Initial state is rendered correctly … And this my wrapping provider

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("appMount")
);

Upvotes: 0

Views: 2263

Answers (2)

Raffael Reichelt
Raffael Reichelt

Reputation: 61

The correct reducer now is:

switch(action.type){
    case MESSAGE:
        return Object.assign({}, state, action.message )
    case SPEAKER:
        return Object.assign({}, state, { speaker });
    default:    
        return state;
}

Upvotes: 0

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36169

You are not returning new state from Object.assign and always returning an old one. Fix:

switch(action.type){
    case MESSAGE:
        return Object.assign({}, state, { message: action.message })
    case SPEAKER:
        return Object.assign({}, state, { speaker });
    default:    
        return state;
}

Upvotes: 2

Related Questions