Next.js Discord

Discord Forum

My Zustand state doesn't change in an async function call but can change on a button click

Unanswered
Polish posted this in #help-forum
Open in Discord
PolishOP
I have an alert dialog that I want to call every time my Zustand state changes via a function call.

In a button onclick, it can change the state and open the alert dialog. But in an async function call, the state doesn't change when that Zustand state change function is called.

Is there something I'm missing regarding async functions and client components vs server components?

This is my Zustand alert store
// src/store/useAlertStore.ts

import { create } from 'zustand'

interface AlertState {
    isAlertOpen: boolean;
    openAlert: () => void;
    closeAlert: () => void;
}

export const useAlertStore = create<AlertState>((set) => ({
    isAlertOpen: false,
    openAlert: () => set({ isAlertOpen: true }),
    closeAlert: () => set({ isAlertOpen: false }),
}));


this is my nav. There is a button with onclick of openAlert

"use client"
import { useAlertStore } from '../../store/useAlertStore';

export function MainNav() {
    const {openAlert} = useAlertStore();

    return (
        <div>
            <nav className="flex items-center gap-4 text-sm lg:gap-6">
                <button onClick={openAlert}>Test Alert</button>
            </nav>
        </div>
    );
}

this is my aysnc function. i called openAlert() but it doesnt open
//src/domain/geofenceControl.ts
import { useAlertStore } from '@/store/useAlertStore';

export async function monitorGeofenceAntennas(data: TagReportingData[]) {
    const { openAlert } = useAlertStore.getState();
    console.log(`Trays detected by geofence antennas on reader ${reader.id}:`);
    openAlert(); //<---- alert called, but doesnt open

}


My full code is here due to discord limit: https://stackoverflow.com/questions/78692577/my-zustand-state-doesnt-change-in-an-async-function-call-but-can-change-on-a-bu

0 Replies