Skip to content

Instantly share code, notes, and snippets.

@msutkowski
Last active April 15, 2020 15:05
Show Gist options
  • Save msutkowski/81a69be15e96028c848bf3764334a323 to your computer and use it in GitHub Desktop.
Save msutkowski/81a69be15e96028c848bf3764334a323 to your computer and use it in GitHub Desktop.
### 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