【发布时间】:2020-11-30 16:27:38
【问题描述】:
我正在试用“@reduxjs/toolkit”v1.4.0
我一直在尝试错误处理。虽然我可以从端点得到错误:
{
"code": "missing_access_key",
"message": "You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]"
}
我无法触发它:
builder.addCase(fetchUsers.rejected, (state, action) => {
// FIXME: rejected not being called on error
state.loading = false
state.error = action.error.message
})
我一直在查看文档,甚至尝试过rejectWithValue。成功后会调用“待定”和“已完成”条件,但我似乎无法触发“拒绝”。我也尝试过 try/catch 块。如果有人能告诉我我做错了什么,将不胜感激。
export const fetchUsers = createAsyncThunk(
'posts/fetchUsers',
async (users: Users) => {
const response: any = await fetch(
`${ENDPOINTS.USERS_SOURCE}tickers/search=${answers.ticker}&access_key=${process.env.MARKET_WATCH_API_KEY}&limit=${RESULTS_LIMIT}`
)
return response.data
}
)
type SliceState = {
error?: null | string
loading: boolean
data: null | SingleUser
selectedData: null | SingleUser
}
// First approach: define the initial state using that type
const initialState: SliceState = {
error: null,
loading: false,
data: null,
}
export const UsersSlice = createSlice({
name: 'Users',
initialState,
reducers: {
clearUsers: (state) => {
state.data = null
},
},
extraReducers: (builder) => {
builder.addCase(fetchUsers.pending, (state) => {
state.data = null
state.loading = true
})
builder.addCase(fetchUsers.fulfilled, (state, action) => {
state.loading = false
state.data = action.payload
})
builder.addCase(fetchUsers.rejected, (state, action) => {
// FIXME: rejected not being called on error
state.loading = false
state.error = action.error.message
})
},
})
export const { clearUsers } = UsersSlice.actions
export default UsersSlice.reducer
【问题讨论】: