I am using recompose in my React project https://github.com/acdlite/recompose/
It's a great library. I'm using the compose
utility as a container component that passes state down as props to the presentational component like so:
const enhance = compose(
lifecycle({
componentDidMount() {
myCall
.getResponse([productId])
.then(products => {
setIsReady(true);
});
},
}),
withState('isAvailable', 'setIsAvailable', false),
withState('isReady', 'setIsReady', false),
mapProps(({
setIsAvailable,
setIsReady,
...state,
}) => ({
onLogoutTouchTap: () => {
...
Note the setIsReady(true)
call within componentDidMount
. This is what I want to do, however lifecycle/componentDidMount doesn't have access to setIsReady
. How can I accomplish my intended result of updating state from componentDidMount
with recompose?
You can and should use this. setState() in only these React lifecycle methods: componentDidMount , componentDidUpdate and componentWillReceiveProps . You can also set it in the componentWillMount method, but it's recommend to use the constructor instead. New in React 16, you can also set it in componentDidCatch .
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
To update state in React components, we'll use either the this. setState function or the updater function returned by the React. useState() Hook in class and function components, respectively.
getDerivedStateFromProps. The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props . It takes state as an argument, and returns an object with changes to the state .
Well I found out if you move the lifecycle
method after the withState
methods, you have access to the setters by accessing this.props.setterFunction
. In my case, here is the solution I was looking for:
const enhance = compose(
withState('isAvailable', 'setIsAvailable', false),
withState('isReady', 'setIsReady', false),
lifecycle({
componentDidMount() {
myCall
.getResponse([productId])
.then(products => {
this.props.setIsReady(true);
});
},
}),
mapProps(({
setIsAvailable,
setIsReady,
...state,
}) => ({
onLogoutTouchTap: () => {
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With