Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react context api with getDerivedStateFromProps?

Tags:

reactjs

Context provides a way to pass data through the component tree without having to pass props down manually at every level. This is great!

but I'm wondering how to use it with getDerivedFromProps()

For example, if I have a prop sent via Context in top level of the app, that said it's window.location.href, and I need to take action in the child component based on the href, e.g. fetch the data.

Using getDerivedStateFromProps(), I have to write something like the following:

getDerivedStateFromProps(nextProps, state) {

  var stateRev = null
  var pathname = hrefToPath(nextProps.href)
  if (pathname != state.pathname) {
    stateRev = {}
    Object.assign(stateRev, {
      pathname,
      book: source.find()
    })
  }
  return stateRev
}

However, if I write the code like the above, I have to send the window.location.href through the levels. What I need to know is if the prop in the context changed, I need to update the state.

I see no way to know the prop in the context changed or not. Is there anything I need to know about the context api and getDerivedStateFromProps?

Thank you.

like image 257
Ben P.P. Tung Avatar asked Jun 18 '19 04:06

Ben P.P. Tung


1 Answers

If you want to consume context in lifecycle methods you can use contextType. The problem with this approach is that getDerivedStateFromProps is static and cannot access instance variables.

So solution I see is to wrap your component in High Order Component, like this

const WithContext = (Component) => {
    return (props) => (
        <CustomContext.Consumer>
            {value =>  <Component {...props} value={value} />}
        </CustomContext.Consumer>
    )
}

In this case you'll get context as part of props

like image 128
Fyodor Avatar answered Oct 21 '22 12:10

Fyodor