|
|
|
|
|
by yiransheng
3291 days ago
|
|
With algebraic data type like in Haskell, the state could be typed like this: data State a =
Loading
| Failed
| Loaded [a]
Compared to a representation like `{ loading:true, error: false, pics:[] }`, the above model has the benefit of "making illegal state not representable".One library in js I like to use to model this type of tagged union / ADT values is single-key[1]. Each variant in a tagged union type is represented by an plain object with just one key, for example: const state1 = { Loading: null };
const state2 = { Failed : <reason> };
const state3 = { Loaded : [...pics] };
The library offers pattern matching syntax on top of this data representation: // render
const reactElement = match(state, {
Loading : () => <Loading />,
Failed : (reason) => <Error {...reason}/>,
Loaded : (pics) => <PicsList pics={pics} />
});
// reducer
const reducer = (state, action) => match(state, {
Loading : () => {
switch (action.type) {
case PICS_FAILURE:
return { Failure: action.payload };
case PICS_SUCCESS:
return { Loaded : action.payload };
default:
return state
}
},
Failed : () => {
switch (action.type) {
case PICS_REQUEST:
return { Loading: true };
default:
return state;
}
},
Loaded : () => {
switch (action.type) {
case PICS_REQUEST:
return { Loading: true };
default:
return state;
}
}
});
[1] https://www.npmjs.com/package/single-key |
|