[英]Redux toolkit using createAsyncThunk and typescript error handling
I have re-read the documentation a few times and can't seem to figure out an error I'm receiving.我已经重新阅读了几次文档,但似乎无法弄清楚我收到的错误。
For some reason I need to define the error type in getAccounts
and accountsSlice
, even though in the documentation it says I shouldn't if I pass rejectValue
type and return rejectWithValue(error as ServerError)
.出于某种原因,我需要在getAccounts
和accountsSlice
中定义错误类型,即使在文档中它说如果我传递rejectValue
类型并return rejectWithValue(error as ServerError)
,我不应该这样做。
interface ServerError {
statusCode: number
description: string
}
export const getAccountsSlice = createAsyncThunk<
GetAccountsState,
{
rejectValue: ServerError
}
>('accountsSlice/getAccounts', async (_, { rejectWithValue }) => {
try {
// handle fulfillment
} catch (error) {
console.error('REQUEST ERROR --', error)
return rejectWithValue(error as ServerError)
}
}
)
export const accountsSlice = createSlice({
name: 'accountsSlice',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(getAccountsSlice.pending, (state) => {
...
})
.addCase(getAccountsSlice.fulfilled, (state, action) => {
...
})
.addCase(getAccountsSlice.rejected, (state, action) => {
return {
...state,
// must add as ServerError or I get an error
error: action.payload as ServerError,
isLoading: false
}
})
}
})
In addition, having rejectValue
typed in createAysncThunk
I get this error when trying to dispatch(getAccounts)
:此外,在rejectValue
中输入了createAysncThunk
我在尝试dispatch(getAccounts)
时收到此错误:
Expected 1 arguments, but got 0.
You should dispatch(getAccounts())
, not dispatch(getAccounts)
.您应该dispatch(getAccounts())
,而不是dispatch(getAccounts)
。
For that you need to type the argument as void
, and that is also where your error is: Generic arguments are positional - the config object is the third argument and you omitted the second.为此,您需要将参数键入为void
,这也是您的错误所在:Generic arguments are positional - config object 是第三个参数,而您省略了第二个。 That way, your getAccounts
expected an argument in the form { rejectValue: ServerError }
.这样,您的getAccounts
需要一个{ rejectValue: ServerError }
形式的参数。
You need to type it你需要输入它
export const getAccountsSlice = createAsyncThunk<
GetAccountsState,
void,
{
rejectValue: ServerError
}
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.