reactjstypescriptreact-hookszustand

Use zustand action in axios query


I am using Zustand in React application, so this the creation of the zustand store

import { create } from 'zustand';

interface IAuth {
  username: string;
  isAuthentificated: boolean;
  updateAuth: (isAuth: boolean) => void;
}

export const useAuth = create<IAuth>((set) => ({
  username: '',
  isAuthentificated: false,
  updateAuth: (isAuth: boolean) => {
    set({ isAuthentificated: isAuth });
  }
}));

and I use it in the api actions

export function UserRegister(username: string, email: string, password: string) {
  api
    .post('/register', { username, email, password })
    .then((data: any) => {
      localStorage.setItem('token', data.token);
      const { updateAuth } = useAuth();
      updateAuth(true);
      console.log('data', data);
      navigate('/chat');
    })
    .catch((error) => {
      // TODO: catch error
      // TODO: add notification
      console.log(error);
    });
}

but it produce a problem:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I expect to have a response how to solve this problem


Solution

  • You can pass it as a function to UserRegister.

    export function UserRegister(username: string, email: string, password: string ,{ onSuccess }: { onSuccess: (data: any) => void}) {
      api
        .post('/register', { username, email, password })
        .then((data: any) => {
          localStorage.setItem('token', data.token);
          onSuccess(true)
          console.log('data', data);
          navigate('/chat');
        })
        .catch((error) => {
          // TODO: catch error
          // TODO: add notification
          console.log(error);
        });
    }
    
    
    ...
    
    // Component code
    const { updateAuth } = useAuth();
    
    UserRegister('username', 'email', 'password', {
        onSuccess: (data: any) => {
          updateAuth(true);
        }
    })
    ...