reactjsreact-cookie

In-component data fetching depending on cookie


I have a component like this:

class MyComponent extends React.PureComponent {
  componentDidMount() {
    const { params } = this.props.match
    fetch(`/o/${params.id}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(r => r.json())
    .then(json => {
      this.props.setData(json)
    })
  }
  render() {
    const { t, payload, cookies } = this.props;
    return <div>
      {cookies.cookies.language}
      {payload.myData}
    </div>
  }
}

So, I fetch my data in the component. But what's important, the resultant data differ depending on one of my cookies. So after changing my cookie I'd like also re-fetch my data, but I don't know what is the most elegant way to do this. I use react-cookie library, so now every cookie change is updated in my view. But of course re-fetching my data in the render method is not a good idea, and I think componentDidUpdate is also a bad place for it. So, how should I solve this problem?

PS. I use Redux too.


Solution

  • You need to have a componentDidUpdate() and inside that you can check if the cookies have changed and then make your fetch call.

    It would be something like this:

    componentDidUpdate(prevProps) {
      if (this.props.cookies !== prevProps.cookies) {
        this.fetchData(this.props.cookies).then(...)
      }
    }
    

    But it looks like this logic along with componentDidMount() should be moved one component up where the component is not pure.