Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proper way to access outside values within the debounced function #35

Closed
alexandr-bbm opened this issue Aug 17, 2019 · 3 comments
Closed

Comments

@alexandr-bbm
Copy link

Hello, I've started using hooks recently and I am sorry if this issue is not related to this lib.

Could you tell me please is there a way to access updated state values within the debounced function? Let me clarify the problem via comments on the minimal example:

function App() {
    const [value, setValue] = useInputState('') // this just encapsulates passing of the e => e.target.value

    console.log({valueInRender: value})
    const [debounced] = useDebouncedCallback(() => {
        // `valueInDebounce` will always be late from the `valueInRender` for 1 character
        // is it possible to overcome somehow without explicit passing of the value?
        console.log({valueInDebounce: value})
    }, 1000)

    const decorateSetState = <T extends Function>(fn: T) => (args: any) => {
        fn(args)
        debounced() // passing args.target.value here is undesired
    }

    const setValueDecorated = decorateSetState(setValue)
    return (
      <div>
        <input onChange={setValueDecorated} value={value}/>
      </div>
    );
}

You can reproduce the issue in the https://stackblitz.com/edit/react-ts-d9udva

@xnimorz
Copy link
Owner

xnimorz commented Aug 17, 2019

Hello, @alexandr-bbm !
Thank you for the issue!

At the moment useDebouncedCallback returns a function, which calls the callback from the render when it was declared. I mean debounced callback calls the function from the previous render. (when value late for 1 char). I'll fix it within 1 or 2 days, and write here when I publish

Right now I made a workaround example: https://codesandbox.io/s/sweet-varahamihira-xkxg8

@xnimorz
Copy link
Owner

xnimorz commented Aug 17, 2019

I've published a new version of the hook: use-debounce@3.0.0 which fixes this issue.

Also I've updated the example: https://codesandbox.io/s/sweet-varahamihira-xkxg8

@alexandr-bbm
Copy link
Author

@xnimorz thank you very much for the quick response and fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants