Dispatch a normal action and a thunk serially. The goal is, when the fetchSomething()
thunk is dispatched, I need to get the latest state value in the async thunk function by thunkAPI.getState()
. The latest state value is {count: 1}
;
import { fetchSomething, testSlice } from './testSlice';
import { useAppDispatch } from './store';
const apiCall = async () => 'remote data';
function App() {
const dispatch = useAppDispatch();
const onClick = async () => {
dispatch(testSlice.actions.increase());
// do something
await apiCall()
dispatch(fetchSomething());
};
return <button onClick={onClick}>click</button>;
}
export default App;
testSlice.ts
:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
export const fetchSomething = createAsyncThunk(
'test/fetchSomething',
async (_, thunkAPI) => {
const state = thunkAPI.getState();
console.log('state: ', JSON.stringify(state, null, 2));
return 'remote data';
}
);
export const testSlice = createSlice({
name: 'test',
initialState: {
count: 0,
},
reducers: {
increase(state) {
state.count = state.count + 1;
},
},
});
After clicking the button, the logs in async thunk:
state: {"test":{"count":1}}
It seems the we can get the latest state value by thunkAPI.getState()
in async thunk. Is this guaranteed?