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

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?

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

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

Can you show where you define the component?

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);

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.

2 Likes

Yes! Now it works! :slight_smile:

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

1 Like

I know this is old as dirt but you SAVED me…
something so silly as generating your component with Component = {…props} = {}
and using “props” inside instead of “this.props”

props is passed in and not recalculated…
this.props is passed in from each new render…

slap Jeez!!!

thanks again!!