react-easy-state – one store triggering change in other with debounce

I’m trying to solve the following pattern using the react-easy-state library: I have two stores containing one string for example:

filter = store({
    search : ""
})

backendFilter = store({
   search : ""
})

I would like that when I call a change to the search in filter it changes the value in backend filter but debounced.

My idea was :

filter = store({
   search : "",
   setFilter(value) {
      filter.search=value;
      backendFilter.setBackendSearchString(value);
   })
}

backendFilter = store({
   search : "",
   setBackendSearchString(string) {
        debounce(
            () => {
                backendFilter.search = string;
            },
            600,
            true
        )();
   },
})

But this is unfortunately not working, just delaying the change but when I use an onChange handler on an input to trigger filter.setFilter the backendFilter is changing as many time as filter just with a little delay. I know in a React component the problem is generally to use useCallback as you have to make sure the function you call in denounce is always the same but couldn’t find a solution to have it work there. Thanks in advance.

Answer

Because you are using debounce(() => {...})() you are basically creating a new function every time you call setBackendSearchString.

I would instead wrap setBackendSearchString in debounce:

backendFilter = store({
  search: "",
  setBackendSearchString: debounce(
    (string) => {
      backendFilter.search = string;
    },
    600,
    true
  ),
});

Al alternative would be to make/use a hook which creates a debounced value for you, like this one: https://github.com/xnimorz/use-debounce

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .