sidharth ramanan
sidharth ramanan

Reputation: 321

React Native : Updating state when props change and internally through setState()

So I have a parent component that passes an array of data to a child component as a prop (the child component saves this array prop as part of its own state), and I want the child's state to update when this prop changes.

I used getDerivedStateFromProps as such :

static getDerivedStateFromProps(props, state) {
    if (props.messages != state.messages) {
        return {
            messages : [ ... props.messages]
        };
    }
    return null;
}

However, I also want to be able to update the state within the child, through setState(). However, when I call setState() to update this.state.messages, the change isn't reflected (presumably because changes to this.state.messages only occur when the props change, as I've overridden getDerivedStateFromProps())

Is there any way I can update the child's state for this.state.messages BOTH when the props change, AND when I want to update it within the child?

My constraints :

Upvotes: 0

Views: 2683

Answers (1)

Huzaifa Ahmed Khan
Huzaifa Ahmed Khan

Reputation: 470

Your parent state is passed to the child component as props. Try using shouldComponentUpdate method in the child component.

shouldComponentUpdate(nextProps){
if(nextProps.messages.length > this.props.messages.length)
    return true
return true;
}

Now use the componentDidUpdate to update your state:

componentDidUpdate(prevProps) {
     // Typical usage (don't forget to compare props):
      if (this.props.messages.length !== prevProps.messages.length) {
        this.setState({
        messages: this.props.messages
        )}
      }
    }

Upvotes: 1

Related Questions