proppy icon indicating copy to clipboard operation
proppy copied to clipboard

Missing didUpdate for componentDidUpdate lifecycle function

Open chimon2000 opened this issue 5 years ago • 3 comments

Attempting to call a state handler using onChange results in an infinite loop. It would be nice if there was a didUpdate function that mirrored the capabilities of (p)react's componentDidUpdate, that allows you to immediately call setState given some conditional.

This feature is important when utilizing routing or similar functionality where a change in props would cause a reset / refetch of data.

As a workaround, calling the state handler in a setTimeout worked fine.

chimon2000 avatar Jul 17 '18 04:07 chimon2000

@chimon2000: Thanks for the issue, Ryan!

onChange is meant for only returning new props (either sync or async), without having any other side-effects.

I will have to dig deeper into how componentDidUpdate can possible work from proppy package.

Could you please share example snippets how you wish to use it? Thanks!

fahad19 avatar Jul 17 '18 14:07 fahad19

Sure, I could see the signature being the similar to onChange

didUpdate(propName, (prop, providers) => void)
didUpdate( (prevProps, nextProps) => true, (props, providers) => void)

Consider the following rudimentary example, where based off of a route change, I want to reset my state.

	...
	//State handler to reset count
    withStateHandlers(
        { count: 10 },
        {
            reset: () => () => ({ count: 0 })
        }
    ),
	//Shorthand syntax.
    didUpdate('user', props => {
        props.reset()
    }),
	//Same thing but with longhand syntax for developer's control.
    didUpdate((prevProps, newProps) => prevProps.user !== newProps.user, props => props.reset(),
	...

Perhaps didUpdate is not the right name for the function, since we really want to execute some handler based the component updating and some additional condition.

chimon2000 avatar Jul 17 '18 20:07 chimon2000

That is a valid use case indeed. I’ll have to think how something like that can be done without risking infinite loop.

If you wanna take a dig at it and start a branch, that would help a lot. I can jump in with the already established test cases then.

fahad19 avatar Jul 17 '18 22:07 fahad19