dispatch()

The dispatch() method is used to trigger state updates through predefined actions. It supports both synchronous and asynchronous actions, and can return values from the actions.

import { createStore } from 'finalstore';
 
const store = createStore({
  states: {
    count: 0,
    user: null as { name: string } | null
  },
  actions: {
    // Sync action with no return
    increment: (state) => {
      state.count++;
    },
    // Sync action with return
    setUser: (state, payload: { name: string }) => {
      state.user = payload;
      return 'success';
    },
    // Async action with return
    fetchUser: async (state, id: string) => {
      const user = await api.getUser(id);
      state.user = user;
      return user;
    }
  },
  selectors: {}
});

Basic Usage

// Sync action with no return
store.dispatch.increment();
 
// Sync action with return value
const result = store.dispatch.setUser({ name: 'John' }); // 'success'

Async Actions

async function loadUser(id: string) {
  // Returns the user from the async action
  const user = await store.dispatch.fetchUser(id);
  console.log('User loaded:', user);
}

Silent Dispatch

For cases where you want to update state without triggering re-renders:

// Using silentDispatch
store.silentDispatch.increment();
store.silentDispatch.setUser({ name: 'John' });
 
// Async actions also work with silentDispatch
await store.silentDispatch.fetchUser('123');

The return values work the same way with both dispatch and silentDispatch.

On this page