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

1 messages · Page 1 of 1 (latest)

muted oliveBOT
#

Hi @sweet folio. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

It seems like you're encountering an issue where the Zustand state doesn't change when called from an async function, but it works fine when called from a button click. This could be related to how the state is being accessed and updated in different contexts.

From the provided code and the knowledge sources, there are a few things to consider:

  1. Ensure Client Component Usage: Make sure that the component or function where you are calling openAlert is a client component. This is crucial because Zustand state management is meant to be used on the client side.

  2. Direct State Access: When accessing Zustand state directly using getState, ensure that the function is executed in a client-side context.

Here is a revised version of your async function to ensure it is executed in a client-side context:

// src/domain/geofenceControl.ts
"use client"
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 doesn't open
}

Adding "use client" at the top of the file ensures that the code is treated as a client component, which is necessary for Zustand to work correctly.

If the issue persists, you might want to check if the async function is being called in a server-side context, which would prevent the state from updating as expected. Ensure that all parts of your code that interact with Zustand are executed on the client side.

#

For more information on using Zustand with Next.js, you can refer to the Zustand documentation (https://zustand.surge.sh/) and the Next.js documentation on client components (https://nextjs.org/docs/getting-started/react-essentials#when-to-use-server-and-client-components).

If you need further assistance, you might find it helpful to look at examples or issues related to Zustand and Next.js, such as the with-zustand example (https://github.com/vercel/next.js/issues/58695) and related discussions.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@sweet folio kapa.ai is still learning and improving, please let us know how it did by reacting below