0

Like many other posts here I am getting the same props in my componentDidUpdate function. Here is the relevant code.

Child

componentDidUpdate(prevProps, prevState) {
    if (prevProps.data !== this.props.data) {
      console.log('Next up mounted')
    }
}

Parent

static async getInitialProps({ query }) {
   const props = axios
      .post('http://localhost:3000/api/club', { clubId: query.clubid })
      .then((res) => {
         //...Do stuff here
         return {
             ...
             data: res.data.payload,
             ...
         }

updatePbd(newBet) {
    let newPbd = [newBet[0]].concat(this.state.clubBetsPending)
    let allBets = this.state.clubBetsResulted.concat(newPbd)
    this.setState({ data: allBets })
}

render() {
    return (<>
        {this.state.data && (
        <NextUp
            data={this.state.data}
        />
        )}
    </>)
}

So in theory, when I call updatePbd and pass it an single array element, it should get appended to the array and update the state causing the child component to run the console log. Firstly it never runs even on first load so shouldn't it always begin prevProps = null and then props = something? Anyway, on run of the function the prevProps and current .props are the same. Thanks

MomasVII
  • 4,641
  • 5
  • 35
  • 52

1 Answers1

0

In this case, the initial prevProps should not be null on first load.

Checking out getInitialProps next.js docs

getInitialProps enables server-side rendering in a page and allows you to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO.

Also, considering that your state is an array, checking it with strict equality (===), it would mean that your check would probably always be true. you might want to check for deep equality checks for your array just in case they all have the same values. Here's a good question with a lot of good answers regarding comparing arrays

How to compare arrays in Javascript

Leomar Amiel
  • 469
  • 3
  • 13