useDebounce does not call function if the component refreshes
Is there an existing issue for this?
- [X] I have searched the existing issues
Have you tried deactivating all plugins except Gutenberg?
- [X] I have tested with all plugins deactivated.
Have you tried replicating the bug using a default theme e.g. Twenty Twenty?
- [X] I have tested with a default theme.
Description
I noticed the issue in the serverSideRenderer component. If the debounce is called but until the fetch function executes the component gets refreshed the debounce call gets cancelled and the fetch is not called https://github.com/WordPress/gutenberg/blob/3da717b8d0ac7d7821fc6d0475695ccf3ae2829f/packages/server-side-render/src/server-side-render.js#L138
Step-by-step reproduction instructions
Use the ServerSideComponent (https://github.com/WordPress/gutenberg/blob/3da717b8d0ac7d7821fc6d0475695ccf3ae2829f/packages/server-side-render/src/server-side-render.js#L138) and force multiple refreshes
Expected Behavior
The debounce function should be called even if the component refreshes.
Current Behavior
The function call is lost on component refresh
Screenshots or screen recording (optional)
No response
Code snippet (optional)
No response
WordPress Information
No response
Gutenberg Information
No response
What browsers are you seeing the problem on?
No response
Device Information
No response
Operating System Information
No response
It seems like the debounced function will cancel if the callback function's reference, arguments or wait time changes: https://github.com/WordPress/gutenberg/blob/a3445ccd3a2f16d923b1bc2873159d8f0cecde01/packages/compose/src/hooks/use-debounce/index.js#L35
The issue is that the ServerSideRender doesn't useCallback on its fetchData function, so a new function is created on each render:
https://github.com/WordPress/gutenberg/blob/3da717b8d0ac7d7821fc6d0475695ccf3ae2829f/packages/server-side-render/src/server-side-render.js#L67
The fix should be to add useCallback to this function. This is mentioned in the docs:
https://github.com/WordPress/gutenberg/blob/a3445ccd3a2f16d923b1bc2873159d8f0cecde01/packages/compose/src/hooks/use-debounce/index.js#L14-L17
@talldan Hello! I worked on this. I wrapped fetchData in a useCallback hook in this manner:
const fetchData = useCallback( () => { });
I ran both the unit tests and the linter, everything passed. Is there anything I should correct or could I open a PR? :)
A PR would be awesome, thanks @saarahasad.
@ciobanu0151 Hello, could you please mention the steps you took to run into this bug, so I could reproduce it and verify the fix? :)
Hi :wave: @talldan, I would like to take this forward :smile:. It would be really helpful if you can share steps to reproduce this behaviour in order to verify and test my changes.
I believe this was fixed via #69237.