Documentation
Concepts
Actions

Actions

Actions help you update your application state. They are the only way to update the state of your application.

Always keep your actions in the same file as the slice and key.

Simple field update

To update a field

  • we create an Action (a function that returns a Transaction) and then use this function to dispatch transaction to update the store.
  • update a field of your slice, you can use the .update method on the field.
import {createKey} from '@nalanda/core';
 
const key = createKey('counterSlice', []);
const counterField = key.field(0);
 
function increment() {
  return counterField.update((val) => val + 1);
}
 
key.effect((store) => {
  store.dispatch(increment());
  // Get the updated state
  counterField.get(store.state); // 1
})

Note: just calling increment() is not enough to update the state. You need to dispatch the action to the store.

Updating many fields

const key = createKey('userDataSlice', []);
 
const userDataField = key.field(undefined);
const isLoadingField = key.field(false);
 
// Update multiple fields of a slice in a single action
function setUserData(data) {
  const txn = key.transaction();
 
  return txn.step((state) => {
    state = state.apply(userDataField.update(data));
    state = state.apply(isLoadingField.update(false));
    return state;
  });
}
 
export const userDataSlice = key.slice({
  setUserData,
});

Merging transactions

You can merge transaction from external actions into your slice's action. This is useful when you want to also change the state of other slices in one single action.

In the example below we merge the transaction from an external setUserData action (see section above):

import { userDataSlice } from './userDataSlice';
// set the userDataSlice as the dependency
const key = createKey('loginSlice', [userDataSlice]);
 
const loggedInField = key.field(false);
 
function loginUser(data) {
  const txn = key.transaction();
 
  return txn.step((state) => {
    // get the transaction from the external action
    const userDataTxn = userDataSlice.setUserData(data);
 
    state = state.apply(userDataTxn);
    state = state.apply(loggedInField.update(true));
 
    // the new state contains both the changes from the external action
    // and the changes from this action
    return state;
  });
}