Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Component constructor store state initialization is inconsistent with component local state initialization #1757

Closed
kromit opened this issue Jul 6, 2021 · 1 comment

Comments

@kromit
Copy link

kromit commented Jul 6, 2021

This is a follow up for a change happened in v6. #1126
I do understand the reasons behind it, but it has introduced some inconsistent behavior between react-redux and react.

What is the current behavior?
Changes/initialization in component state in the constructor are available in the first render pass. It is guaranteed that the component is rendered only once with the correct local state.

Changes in redux store state in the component constructor are not available in the first render pass. The component is rendered using old store state in the first pass and causes a second render pass. The store state also may contain data from previous mounts, but since it is currently not possible to reset the store state from the constructor, old data is rendered in the first render pass.

class Comp extends Component {
  constructor(props){
     super(props);   
     const time = new Date();
      
      // init local state 
      this.state={
           time
           isLoading: true
     }

     // init store state
     props.dispatch({
        type:'INIT_OR_RESET', 
        payload:{
           time,
           isLoading: true
        }
      })
  }

  render (){
    const {myStoreState} = this.props;
    
    if(myStoreState.time != this.state.time){
      console.error("inconsistency");      
    } 

    ....
  }
}

What is the expected behavior?

Store state changes made in constructor should be available in the first render pass. Otherwise there should be an option for reset/init store state before the first render pass.

@timdorr
Copy link
Member

timdorr commented Jul 6, 2021

Unfortunately, this isn't possible. There is no intermediate step between constructor and render that we can use to update the props provided to the connected component. The connect wrapper component has already been constructed and obtained the selected state from the store. If you check props in the constructor, you'll see it has old state data as well. React doesn't provide a way for us to intervene and update those props before rendering.

@timdorr timdorr closed this as completed Jul 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants