ferp-js
Search…
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:
1
const SimpleAction = (state) => [state, effects.none()];
Copied!
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:
1
import { effects } from 'ferp';
2
3
const MyEffect = (text) => effects.thunk(() => {
4
console.log('MyEffect', text);
5
return effects.none();
6
});
7
8
const IncrementCounterAndPrint = (state) => [
9
{ ...state, counter: state.counter + 1 },
10
MyEffect('incremented'),
11
];
Copied!

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:
actions.js
todoFx.js
1
import { effects } from 'ferp';
2
import * as todoFx from './todoFx.js';
3
4
export const AddTodo = (todo) => (state) => [
5
{ ...state, todos: state.todos.concat(todo) },
6
effects.none(),
7
];
8
9
export const RequestTodo = (todoId) => (state) => [
10
state,
11
todoApi.getTodo(state.external.fetch, todoId, AddTodo),
12
];
Copied!
1
import { effects } from 'ferp';
2
3
export const getTodo = (fetchFn, id, onSuccess, onFailure) => effects.defer(
4
fetchFn(`https://jsonplaceholder.typicode.com/todos/${id}`)
5
.then(response => response.json())
6
.then(data => effects.act(onSuccess(data)))
7
.catch((err) => (
8
onFailure
9
? effects.act(onFailure(err))
10
: effects.none()
11
))
12
);
Copied!
Last modified 2mo ago