5 ms·
Not sure which specific issues you encountered, but I had issues with defining actions and using their types in a union to the reducer. There is a nice little
by emptysea 8y ago
Not sure which specific issues you encountered, but I had issues with defining actions and using their types in a union to the reducer.
There is a nice little library [1] that fixes this issue.
So a general redux setup looks as follows:
const FETCH_USERS_BEGIN = "@@FOO/FETCH_USERS_BEGIN"
const FETCH_USERS_SUCCESS = "@@FOO/FETCH_USERS_SUCCESS"
const FETCH_USERS_ERROR = "@@FOO/FETCH_USERS_ERROR"
const fetchUsersBegin = () => action(FETCH_USERS_BEGIN)
const fetchUsersSuccess = (users: IUser[]) => action(FETCH_USERS_SUCCESS, users)
const fetchUsersError = () => action(FETCH_USERS_ERROR)
type IActions =
| ReturnType<typeof fetchUsersBegin>
| ReturnType<typeof fetchUsersSuccess>
| ReturnType<typeof fetchUsersError>
interface IUser {
id: number
name: string
}
interface IState {
readonly isLoading: boolean
readonly isErrorLoading: boolean
readonly allIds: number[]
readonly byId: {
readonly [key: number]: IUser
}
}
const defaultState = {
isLoading: false,
isErrorLoading: false,
allIds: [],
byId: {}
}
const reducer = (state: IState = defaultState, action: IActions) => {
// narrowing on types
switch (action.type) {
case FETCH_USERS_BEGIN:
return { ...state, isLoading: true, isErrorLoading: false }
case FETCH_USERS_SUCCESS:
return {
...state,
byId: action.payload.reduce(
(acc, u) => ({ ...acc, [u.id]: u }),
{}
),
allIds: action.payload.map(u => u.id),
isLoading: false,
isErrorLoading: false
}
case FETCH_USERS_ERROR:
return {
...state,
isLoading: false,
isErrorLoading: true
}
default:
return state
}
}
[1]: https://github.com/piotrwitek/typesafe-actions#1-classic-js-style-with-constants-ftw https://github.com/piotrwitek/typesafe-actions#1-classic-js-...
- mezzode 8y agoI've found myself preferring type guards for checking action type, since it avoids you having to have keep one big `Actions` union around that takes X amount of lines and really doesn't serve any other purpose.