Skip to content
This repository was archived by the owner on Apr 3, 2024. It is now read-only.

Commit 098a43f

Browse files
committed
Add docs
1 parent 8332fb9 commit 098a43f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

README.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ If you know how to [`useReducer`](https://reactjs.org/docs/hooks-reference.html#
1616
- [Quick Start](#quick-start)
1717
- [Named Effects](#named-effects)
1818
- [Effect Implementations](#effect-implementations)
19+
- [Initial Effects](#initial-effects)
1920
- [Effect Entities](#effect-entities)
2021
- [Effect Cleanup](#effect-cleanup)
2122
- [Replacing Effects](#replacing-effects)
@@ -216,6 +217,43 @@ const [state, dispatch] = useEffectReducer(someReducer, initialState, {
216217
});
217218
```
218219

220+
## Initial Effects
221+
222+
The 2nd argument to `useEffectReducer(state, initialState)` can either be a static `initialState` or a function that takes in an effect `exec` function and returns the `initialState`:
223+
224+
```js
225+
const fetchReducer = (state, event) => {
226+
if (event.type === 'RESOLVE') {
227+
return {
228+
...state,
229+
data: event.data,
230+
};
231+
}
232+
233+
return state;
234+
};
235+
236+
const getInitialState = exec => {
237+
exec({ type: 'fetchData', someQuery: '*' });
238+
239+
return { data: null };
240+
};
241+
242+
// (in the component)
243+
const [state, dispatch] = useEffectReducer(fetchReducer, getInitialState, {
244+
fetchData(_, { someQuery }) {
245+
fetch(`/some/api?${someQuery}`)
246+
.then(res => res.json())
247+
.then(data => {
248+
dispatch({
249+
type: 'RESOLVE',
250+
data,
251+
});
252+
});
253+
},
254+
});
255+
```
256+
219257
## Effect Entities
220258

221259
The `exec(effect)` function returns an **effect entity**, which is a special object that represents the running effect. These objects can be stored directly in the reducer's state:
@@ -348,6 +386,27 @@ const SomeComponent = () => {
348386
};
349387
```
350388

389+
The 2nd argument to `useEffectReducer(...)` can either be a static `initialState` or a function that takes in `exec` and returns an `initialState` (with executed initial effects). See [Initial Effects](#initial-effects) for more information.
390+
391+
```js
392+
const SomeComponent = () => {
393+
const [state, dispatch] = useEffectReducer(
394+
someEffectReducer,
395+
exec => {
396+
exec({ type: 'someEffect' });
397+
return someInitialState;
398+
},
399+
{
400+
someEffect(state, effect) {
401+
// ...
402+
},
403+
}
404+
);
405+
406+
// ...
407+
};
408+
```
409+
351410
Additionally, the `useEffectReducer` hook takes a 3rd argument, which is the implementation details for [named effects](#named-effects):
352411

353412
```js

0 commit comments

Comments
 (0)