Skip to content

Instantly share code, notes, and snippets.

@MarceloAlves
Last active December 19, 2019 01:36
Show Gist options
  • Save MarceloAlves/d1e4f8ba39ac704629400f55d3106b5f to your computer and use it in GitHub Desktop.
Save MarceloAlves/d1e4f8ba39ac704629400f55d3106b5f to your computer and use it in GitHub Desktop.
import { createSlice as createSliceToolkit } from '@reduxjs/toolkit'
export interface StateSlice<T = any> {
data: T
isFetching: boolean
receivedAt: number | null
error: boolean
errorMessage: string | null
errorCode: number | null
}
const requestStart = state => {
state.isFetching = true
}
const requestSuccess = (state, { payload }) => {
state.isFetching = false
state.error = false
state.data = payload
}
export const createSlice = ({
name,
initialState,
reducers,
extraReducers
}): {
name: string
initialState: StateSlice
reducers?: Record<string, CaseReducer<StateSlice, AnyAction>>
extraReducers?: Record<string, CaseReducer<StateSlice, AnyAction>>
} => {
return createSliceToolkit({
name,
initialState,
reducers: {
requestStart,
requestSuccess,
...reducers
})
}
/**
* The actions in createSlice.actions end up being typed as
*
* const requestStart: void | WithTypeProperty<WithMatch<() => WithPayload<undefined, Action<string>>, string, undefined, never, never>, string> | WithTypeProperty<WithMatch<{
* (payload?: undefined): WithPayload<undefined, Action<string>>;
* <PT extends unknown>(payload?: PT | undefined): WithPayload<PT, Action<string>>;
* }, string, unknown, never, never>, string>
*
* Which results in a "This expression is not callable error"
*
* createSlice.reducers doesn't really like Record<string, CaseReducer<StateSlice, AnyAction>> either
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment