0

I am trying to make one of my components update if the length of an array in props does not match the previous. The problem is I make a redux action fire on componentWillMount. So when I pass this.props.array to the function in shouldComponentUpdate its initially empty and so it doesnt work how I want.

Im wondering if anyone has advice or knows a better way/fix for this? Thanks in advance.

     componentDidMount() {
    this.props.getAllCourses(this.props.user.id);
  }

  shouldComponentUpdate(nextProps) {
    return compareCoursesProps(nextProps, this.props.courses);
  }

  render() {
Kai Ferrall
  • 81
  • 2
  • 12
  • Please provide some code. Thanks. – Marko Savic Oct 25 '18 at 21:13
  • A component that receive different props should update automatically, also `componentWillMount` is considered [unsafe](https://reactjs.org/docs/react-component.html#unsafe_componentwillmount) and should be avoided in new code. If you want to dispatch an action do it in componentDidMount instead. – Asaf Aviv Oct 25 '18 at 21:13
  • @MarkoSavic Added the code above. Thanks – Kai Ferrall Oct 25 '18 at 21:18

1 Answers1

0

You can use getDerivedStateFromProps lifecycle for it. This might güve you an idea

    state = { yourArray:[] }

static getDerivedStateFromProps(nextProps, prevState)      {
if (nextProps.yourArray !== prevState.yourArray) {
    return { yourArray: nextProps.yourArray};
}
return null;
}
oakar
  • 1,187
  • 2
  • 7
  • 21