Reputation: 672
I'm trying to call an API endpoint using @reduxjs/toolkit and typescript.
I've followed the example here, without success https://redux-toolkit.js.org/api/createAsyncThunk
I'm stuck on some typescript errors, what am I doing wrong?
1°error: when I do the dispatch like that in MessageController.tsx , typescript says: Argument of type 'AsyncThunk<any, void, {}>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type 'AsyncThunk<any, void, {}>' but required in type 'AnyAction'.ts(2345) index.d.ts(19, 3): 'type' is declared here.
2° error: in message.slice.ts everytime I do a message.fulfilled or rejected or pending I get this: Property 'fulfilled' does not exist on type '(data: any) => AsyncThunk<any, void, {}>'.ts(2339)
message.slice.ts
export const sendMessage = ( data) =>createAsyncThunk(
`message/sendMessage`,
async (data, thunkAPI) => {
const response = await axios.post
( `/api/v1/xxx/test-messages`,
data,
httpOptions(getDefaultHeaders()));
return response.data;
}
)
const messageSlice = createSlice({
name: "message",
initialState: {
message: {},
loading: "idle",
error: "",
},
reducers: {},
extraReducers: (builder) => {
builder.addCase(sendMessage.pending, (state) => {
state.message = {};
state.loading = "loading";
});
builder.addCase(
sendMessage.fulfilled, (state, { payload }) => {
state.message = payload;
state.loading = "loaded";
});
builder.addCase(
sendMessage.rejected,(state, action) => {
state.loading = "error";
state.error = action.error.message;
});
}
})
interface stateI{
message: messageI;
}
interface messageI{
loading: string;
}
export const selectMessage = createSelector(
(state: stateI) => ({
message: state.message,
loading: state.message.loading,
}), (state) => state
);
MessageController.tsx
import {useAppDispatch} from '../../state/store';
const dispatch = useAppDispatch();
const { message } = useSelector(selectMessage);
React.useEffect(() => {
console.log(message)
// TODO display the result of the api call in the page..
}, [message]);
const handleClick =()=>{
const data = {
"environment": dropboxValue,
"payload": textareaValue
};
dispatch(sendMessage(data))
.then(() => {
// TODO display the result of the api call in the page..
})
}
//additional ui code for a button which when clicked trigger the api call (sendMessage)
store.ts
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
//other code not relevant (I think)
Upvotes: 1
Views: 2821
Reputation: 12779
Case 1: You createuseAppDispatch
wrong. Update can like this:
export const useAppDispatch = useDispatch<AppDispatch>();
Case 2: You create thunk action wrong. You can update like this:
export const sendMessage = createAsyncThunk(
`message/sendMessage`,
async (data, thunkAPI) => {
...
Upvotes: 4