Also about exercise 2, extra credit 3... The solution has this:
function asyncReducer(state, action) {
switch (action.type) {
case 'pending': {
return {status: 'pending', data: null, error: null}
}
case 'resolved': {
return {status: 'resolved', data: action.data, error: null}
}
case 'rejected': {
return {status: 'rejected', data: null, error: action.error}
}
default: {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
function useAsync(initialState) {
const [state, unsafeDispatch] = React.useReducer(asyncReducer, {
status: 'idle', data: null, error: null, ...initialState,
})
const dispatch = useSafeDispatch(unsafeDispatch)
const {data, error, status} = state
const run = React.useCallback(
promise => {
dispatch({ type: 'pending' })
promise.then(
data => { dispatch({ type: 'resolved', data }) },
error => { dispatch({ type: 'rejected', error }) },
)
},
[dispatch],
)
return { error, status, data, run }
}
aside from not following convention, why is it not advisable to do this instead?
function asyncReducer(state, action) {
const possibleStatus = ['pending', 'resolved', 'rejected']
if (possibleStatus.includes(action.status)) {
return action
}
throw new Error(`Status is not handled: ${action.status}`
}
function useAsync(initialState) {
const [state, unsafeDispatch] = React.useReducer(asyncReducer, {
status: 'idle', data: null, error: null, ...initialState,
})
const dispatch = useSafeDispatch(unsafeDispatch)
const {data, error, status} = state
const run = React.useCallback(
promise => {
dispatch({ status: 'pending' })
promise.then(
data => { dispatch({ status: 'resolved', data }) },
error => { dispatch({ status: 'rejected', error }) },
)
},
[dispatch],
)
return { error, status, data, run }
}
A reply
My response: