Writing Your Own Actions

Actions are absolutely tied to your application, but good news, they are just basic functions, so they are easy to write. Check out this very simple action:

const SimpleAction = (state) => [state, effects.none()];

Sure, it doesn't do anything, but it's an action!

Actions with Side-Effects

If you haven't already read about Composing Custom Effects, go check out that section before continuing.

Up until this point, we've mostly dealt with basic actions that have no side-effects. More good news, actions always return a state and a single (side) effect. Yes, a valid side effect is effects.none(), meaning no side effect.

As you would expect from the examples so far, writing an effect into an action is simple:

import { effects } from 'ferp';

const MyEffect = (text) => effects.thunk(() => {
  console.log('MyEffect', text);
  return effects.none();

const IncrementCounterAndPrint = (state) => [
  { ...state, counter: state.counter + 1 },

Best Practices

Actions import Effects, Effects accept Action parameters

One thing I found immediately while writing state management with actions and effects is it is incredibly easy to have issues with circular dependencies. For instance, often times actions can trigger effects, and those effects may trigger more actions. If your actions and effects are in separate files, how do you import things to prevent Node from having a circular dependency? The formula that works for me is letting my actions module import any and all effect modules, but forcing effect methods to have actions passed to them. Here's an example of how that can look:

import { effects } from 'ferp';
import * as todoFx from './todoFx.js';

export const AddTodo = (todo) => (state) => [
  { ...state, todos: state.todos.concat(todo) },

export const RequestTodo = (todoId) => (state) => [
  todoApi.getTodo(state.external.fetch, todoId, AddTodo),

Last updated