skip to Main Content

I’m trying to validate the input after the API request. It looks like value hasErrors is not updated within a validation function. Only after the rerender it gets the value.

And – yes I tried many things like useCallback, setting the state to force rerender

Maybe you can spot the issue

https://stackblitz.com/edit/vitejs-vite-hj9vsw?file=src%2FApp.tsx

I tried to do the same with formik and swr and got it working

https://stackblitz.com/edit/vitejs-vite-2ccgg9?file=src%2FApp.tsx

Finally, it works now – special thank-you goes to AI for the ideas

https://stackblitz.com/edit/vitejs-vite-dzd5wd?file=src%2FApp.tsx

2

Answers


  1. Chosen as BEST ANSWER

    So the problem was in a different spot. Make sure that your custom hooks are correctly returning values. If you extract them before returning - they loose track of changes.

    https://stackblitz.com/edit/vitejs-vite-gpdnjb?file=src%2FApp.tsx


  2. Here is a solution using async await in the validate method. awaiting refetch. You can cause this error by passing in id 0. It’s a small tweak to your first example.

    const validate = async (value: string) => {
        if (value.length > 3) {
          const result = await refetch();
    
          console.log({ result });
          if (!result.data.id) {
            return 'Error no such todo';
          }
    
          return true;
        }
    
        return false;
      };
    

    Here is the working example: https://stackblitz.com/edit/vitejs-vite-foxtb6?file=src%2FApp.tsx

    The issue you are having is that you are trying to refetch and then read a state update while inside of a function call.

    It’s the same problem that many people have in React when they update state in a function then immediately try to read that state and discover that state hasn’t updated yet. Changes in state do not show up until the next render. You can’t set state in a function then immediately expect to be able to read that updated state in the same function call. That is what is happening when you call refetch in the validate method. When refetch resolves it updates state being return from useQuery and you are trying to read those state updates in the same function that called refetch.

    In my example, by awaiting refetch we get the values directly from the result of the refetch. That result is not stateful and can be read immediately.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search