The state is correctly mutated and returned but view does not rerender


#1

I’ve followed this guide, a new state object with updated propery is returned, but nothing, the view doesn’t update.

/* Events component */
const mapStateToProps = (state) => {
  return {
    text: state.eventsReducer.text
  }
}
/* eventsReducer */
const initialState = {
  text: 'This is a text!'
}

const eventsReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'CHANGE_TEXT':
      console.log('Initial state:', state);
      const newState = Object.assign({}, state, { text: 'This is a new text' });
      console.log('New state:', newState);
      return newState;
    default:
      return state;
  }
}

export default eventsReducer;

Where I’m doing wrong?


#2

Can you show where you’re using connect to attach the Redux data to your component?


#3

Uhm, I’m not in a container, I’m in the same file of the component, may be this is the problem?


#4

Can you show where you define the component?


#5

The path is: imports/ui/components/Events.js

The content of the component file is

import React from 'react';
import { connect } from 'react-redux';

import { changeText } from '../redux/actions';

class Events extends React.Component {
  constructor(props) {
    super(props);

    this.text = props.text;
    this.onClick = props.onClick;
  }

  render() {
    return (
      <div className="events-container">
        <h2>Events</h2>
        <a onClick={this.onClick}>Click Me</a>
        <h3>{this.text}</h3>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    text: state.eventsReducer.text
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onClick: () => {
      dispatch(changeText())
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Events);

#6

That’s the problem.

The constructor is only called once, when the component is rendered. You need to use this.props.text in your render function directly.


#7

Yes! Now it works! :slight_smile:

Thank you so much @sashko, both for the help and explanation! :thumbsup: