I'm trying to implement react redux toolkit into my application. Everything went fine, but I will need a async function. I was following the basic docs to implement it but I don't know the cause of this issue.
The first issue is regarding to typescript, this file is the Stock.store.ts
:
import { createSlice } from '@reduxjs/toolkit';
import { AppDispatch, AppThunk } from '.';
const stock = createSlice({
name: 'stock',
initialState: {
counter: 0,
},
reducers: {
increment(state) {
state.counter = 1;
},
decrement(state) {
state.counter -= 1;
},
},
});
export const { increment, decrement } = stock.actions;
export default stock.reducer;
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function asyncIncrement(): AppThunk {
// Error here
return async function (dispatch: AppDispatch) {
await sleep(3000);
dispatch(increment());
};
}
Error image: This is the main redux file:
import { Action, configureStore, ThunkAction } from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';
import stockReducer from './Stock.store';
const store = configureStore({
reducer: {
stock: stockReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export type AppThunk = ThunkAction<void, RootState, null, Action<string>>;
export const useAppDispatch = () => useDispatch<AppDispatch>();
export default store;
The second one is trying to implement the call into a component:
This is a piece of the App.tsx
:
// Redux
import { Provider } from 'react-redux';
import store from './src/redux';
export default function App() {
return (
<ThemeProvider theme={theme}>
{!isAuthenticated ? (
<NavigationContainer>
<AuthRoutes></AuthRoutes>
</NavigationContainer>
) : (
<Provider store={store}>
<Main />
</Provider>
)}
</ThemeProvider>
);
}
CodePudding user response:
Inside the thunk, where you have (dispatch: AppDispatch)
, remove the : AppDispatch
part. That's already implied by the AppThunk
usage right before it.