How to use next redux wrapper with redux toolkit without typescript?
tempcoderr opened this issue · 1 comments
tempcoderr commented
I have a redux store created using javascript, and I am unable to use next redux wrapper with it.
Here is my slice:
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import { HYDRATE } from "next-redux-wrapper";
export const getCurrentUser = createAsyncThunk(
"counter/getCurrentUser",
async () => {
const res = await axios.get("http://localhost:8000/get-current-user", {
withCredentials: true,
});
return res.data;
}
);
const userSlice = createSlice({
name: "user",
initialState: {
username: null,
email: null,
firstName: null,
lastName: null,
gender: null,
dob: null,
},
reducers: {
changeUser: (state, action) => {
return action.payload;
},
clearUser: () => {
return {
username: null,
email: null,
firstName: null,
lastName: null,
gender: null,
dob: null,
};
},
},
// extraReducers(builder) {
// builder.addCase(getCurrentUser.fulfilled, (state, action) => {
// return action.payload;
// });
// },
extraReducers: {
HYDRATE: (state, action) => {
console.log("HYDRATE", state, action.payload);
return {
...state,
...action.payload.subject,
};
},
},
});
export const { changeUser, clearUser } = userSlice.actions;
export default userSlice.reducer;
Here is my store code:
// TODO add HYDRATE wrapper nextjs
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./userSlice";
import emailReducer from "./emailSlice";
import { createWrapper } from "next-redux-wrapper";
const makeStore = () =>
configureStore({
reducer: {
user: userReducer,
email: emailReducer,
},
devTools: true,
});
export const wrapper = createWrapper(makeStore);
Here is my _app.js
component:
function MyApp({ Component, ...rest }) {
const router = useRouter();
const { store, props } = wrapper.useWrappedStore(rest);
const { pageProps } = props;
return (
<>
<Provider store={store}>
<Header />
<AnimatePresence initial={false} mode="wait">
<App>
<Component {...pageProps} key={router.pathname} />
</App>
</AnimatePresence>
</Provider>
</>
);
}
const App = ({ children }) => {
const dispatch = useDispatch();
useEffect(() => {
console.log("Calling dispatch in backend");
dispatch(getCurrentUser());
});
return <>{children}</>;
};
export default wrapper.withRedux(MyApp);
This code does not work, what am I doing wrong here?
kirill-konshin commented
Please create a codesandbox. Closing this one.
Normally to convert TS->JS you just omit types and everything works. You can also switch to JS examples in the readme, just expand appropriate blocks.