I'm using next-redux-wrapper, and on my wrapper.getServersideProps I'm dispatching a thunk, but during hydration it's action returns a payload of same value of initial state. Why?
My Thunk:
export const fetchData = createAsyncThunk<IData>(
"fetch-data",
async () => {
const res = await fetch(
"https://..."
);
const data: Promise<IData> = res.json();
console.log("data", data) //it's able to fetch the data;
return data;
}
);
My extraReducers:
builder.addCase(HYDRATE, (state, action: AnyAction) => {
// the action.payload has the same value of initial state (not updated)
console.log("data-action", action.payload.mySlice);
if (!action.payload.mySlice.data) {
return state;
}
state.data = action.payload.mySlice.data;
});
builder
.addCase(fetchData.fulfilled, (state, action) => {
console.log("fulfilled");
// action.payload is correct and return fetched data from API
state.data = action.payload;
state.error = false;
state.loading = false;
})
getServerSideProps:
export const getServerSideProps = wrapper.getServerSideProps(
(store) =>
async ({ params }) => {
await store.dispatch(fetchData());
return {
props: {},
};
}
);
I also tried dispatching the data inside my thunk, but didn't work either.
Update
Now it works but only when I dispatch data inside the thunk after, adding an await before store.dispatch(fetchData()).