00
:
00
:
00
:
00
Corso SEO AI - Usa SEOEMAIL al checkout per il 30% di sconto

Azioni Async

Async/Await

In Zustand, le azioni asincrone sono supportate nativamente. Non servono middleware come redux-thunk o redux-saga. Basta rendere la funzione async.

```tsx interface FishState { fishes: number loading: boolean fetchFishes: () => Promise }

const useFishStore = create((set) => ({ fishes: 0, loading: false, fetchFishes: async () => { // 1. Setta loading true set({ loading: true })

// 2. Chiamata API
const response = await fetch('/pond')
const fishes = await response.json()

// 3. Setta risultato e loading false
set({ fishes: fishes, loading: false })

}, })) ```

Accesso allo stato corrente (get)

Se hai bisogno di leggere lo stato attuale dentro un’azione (es. per non rifare una fetch se ho già i dati), usa get().

```tsx fetchFishes: async () => { const { fishes } = get() if (fishes > 0) return // Dati già presenti, esci

// ... fetch ...

} ```