Currently working on developing a reusable useReducer
hook with typings.
Below is the existing code:
type State<T> = {
data?: T
isLoading: boolean
error?: string
}
type Action<T> =
| { type: "request" }
| { type: "success"; results: T }
| { type: "failure"; error: string }
function reducer<T>(state: State<T>, action: Action<T>): State<T> {
switch (action.type) {
case "request":
return { isLoading: true }
case "success":
return { isLoading: false, data: action.results }
case "failure":
return { isLoading: false, error: action.error }
}
}
export function useFetchState<T>() {
return useReducer(reducer<T>, {isLoading: false});
}
The purpose of this hook is to handle fetch state while allowing for dynamic data, making it versatile for various contexts:
const [videoFetch, dispatchVideo] = useFetchState<Video[]>()
const [userFetch, dispatchUser] = useFetchState<User[]>()
An issue arises where the expression reducer<T>
throws an error stating Error:(26, 20) TS2345: Argument of type 'boolean' is not assignable to parameter of type 'Reducer'., yet excluding T
leaves the data type unknown.
I would appreciate any insights on how to address this situation in TypeScript and achieve my desired outcome.
Thank you for your assistance.