score:1

Accepted answer

Yes, you can dispatch action in constructor to change reducer state

constructor(prop){
    super(prop);
    prop.dispatch(action);
}

Another approach you can try is setting default props so that you don't need to call reducer(dispatch action)

ButtonComponent.defaultProps = {
  message: defaultValue,
};

score:0

One possible solution I can think of...

If you could go with the first approach, you can try to stop the previous state being shown while component is being re-rendered with reset state.

The only phase during which you would see the prevState is during the initial render. How about an instance variable to track the render count.

A rough draft.

import React from "react";
import { connect } from "react-redux";
import { add, reset } from "./actions";
class Topics extends React.Component {

  renderCount = 0;

  componentDidMount() {
    // Dispatch actions to reset the redux state
    // When the connected props change, component should re-render
    this.props.reset();
  }

  render() {
    this.renderCount++;
    if (this.renderCount > 1) {
      return (
        <div>
          {this.props.topics.map(topic => (
            <h3 id={topic}>{topic}</h3>
          ))}
        </div>
      );
    } else {
      return "Initializing"; // You can return even null
    }
  }
}

const mapStateToProps = state => ({ topics: state });
const mapDispatchToProps = (dispatch) => {
  return {

    add(value){
      dispatch(add(value));
    },
    reset(){
      dispatch(reset());
    }
  }
}

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

Here renderCount is a class variable, that keeps incrementing on component render. Show a fallback UI on first render to avoid previous state from being shown and on second render (due to redux store update), you could display the store data.

A working example added below. I have added an approach to avoid the fallback UI as well. Have a look if it helps.

https://stackblitz.com/edit/react-router-starter-fwxgnl?file=components%2FTopics.js


Related Query

More Query from same tag