Last active
April 15, 2020 15:05
-
-
Save msutkowski/81a69be15e96028c848bf3764334a323 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Recipes for typing createAsyncThunk | |
// Typing with Generics | |
const withGenerics = createAsyncThunk< | |
{ banana: string }, | |
string, | |
{ state: RootState } | |
>('test/usingGenerics', (arg, { getState }) => { | |
const { test } = getState() | |
return { | |
banana: 'test' | |
} | |
}) | |
// Generic typing and allowing an optional arg | |
const withOptionalArg = createAsyncThunk< | |
{ banana: string }, | |
string | void, | |
{ state: RootState } | |
>('test/withOptionalArg', (arg, { getState }) => { | |
const { test } = getState() | |
if (arg) { | |
// Do something with the arg if it exists | |
} | |
return { | |
banana: 'test' | |
} | |
}) | |
// Inline typing with an optional arg | |
const withOptionalArgInline = createAsyncThunk('test/withOptionalArgInline', (arg: string | void, { getState }) => { | |
const { test } = getState() as RootState | |
return { | |
banana: 'test' | |
} | |
}) | |
// Unused arg, but has access to thunkApi | |
const optionalWithGetState = createAsyncThunk('test/optionalWithGetState', (_: void, thunkApi) => { | |
const { test } = thunkApi.getState() as RootState | |
// Do something with the state here, make an api request, etc. | |
return { | |
banana: 'test' | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment