Search code examples
reactjszustand

Zustand useStore - arg is undefined on re-render


I have a Zustand store that's misbehaving after I login to my app and update the store.

Here's my store:

import {create} from 'zustand'

import {ITRUserInfoDTO, LoginResponse} from "../itr-client";

export type UserContextValue = {
    credentials: LoginResponse | null,
    expiration: number | null,
    user: ITRUserInfoDTO | null
}

export interface AuthState extends UserContextValue {
    loggedIn: (ctx: UserContextValue) => void
    logout: () => void
}

export const LOGGED_OUT_USER_CONTEXT: UserContextValue = {
    credentials: null,
    expiration: null,
    user: null
}

export const useAuthStore = create<AuthState>(
    (set) => ({
        ...LOGGED_OUT_USER_CONTEXT,
        loggedIn: (ctx: UserContextValue) => set((state) => set({...ctx})),
        logout: () => set((state) => set({...LOGGED_OUT_USER_CONTEXT,}))
    }));

Here's my component:

export default function LoginPage() {
    const {user, loggedIn} = useAuthStore(useShallow(a => ({user: a.user, loggedIn: a.loggedIn})))
    const [searchParams, setSearchParams] = useSearchParams();
    const redirectLocation = searchParams.get('redirect');
    const navigate = useNavigate()

    const go = () => redirectLocation > 0 ? navigate(redirectLocation, {replace: true}) : navigate('/home', {replace: true});
    // useEffect(() => {
    //     if (user) {
    //         go()
    //     }
    // })

    const tryLogin = useCallback((loginDTO) => {
        const authApi = new AuthenticationApi();
        authApi.authenticate({loginDTO})
            .then(loginResult => {
                const configuration = new Configuration({accessToken: loginResult.token});
                const userInformationApi = new UserInformationApi(configuration);
                userInformationApi.getMe().then(me => {
                    const cu = {
                        credentials: loginResult,
                        expiration: new Date().getTime() + loginResult.expiresIn,
                        user: me,
                    }
                    // alert(JSON.stringify(cu))
                    loggedIn(cu)
                }).catch(e => {alert(`Error: ${JSON.stringify(e)}`); console.error(e)});
            })
            .catch(error => console.error('Error', error))
            .finally(() => console.log("Done logging in"))
    }, [loggedIn, user])

I login fine, and in my callback after I call loggedIn(cu) I get an error.

I think the page re-renders and throws the error, which is:

Uncaught TypeError: a is undefined

This clearly refers to useAuthStore(useShallow(a => ( being called on re-render with a undefined.

What gives here? This seems pretty simple but I can't get it to work...


Solution

  • From the Zustand documentation, state can be updated as:

    import { create } from 'zustand'
    
    const useStore = create((set) => ({
      bears: 0,
    
      // based on previous state
      increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
    
      // without using the previous state
      removeAllBears: () => set({ bears: 0 }),
      updateBears: (newBears) => set({ bears: newBears }),
    }))
    

    You seem to have combined both ways in your code:

    // This line is the issue
    loggedIn: (ctx: UserContextValue) => set((state) => set({...ctx})),
    
    // Fix:
    loggedIn: (ctx: UserContextValue) => set({...ctx}),
    logout: () => set({...LOGGED_OUT_USER_CONTEXT}))
    

    What actually happened:

    1. The state is set correctly: set({...ctx}).
    2. The state is set again as what the set() function returns (void, i.e. undefined): set((state) => undefined).