Reputation: 65
i am trying to build basic e-cart. My problem is that during sign up , information coming from the server is store in redux store and i also store in localstorage , it also save there , but sign up page is not redirecting to home page , in case of successful sign up. Here i am applying logic that if user is not null in store than it should be redirected to home page. It is only working when i manually refresh page , and then all time it works fine. So how to deal with this problem?
Here is my App.js file code
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route path="/signUp" component={SignUp} />
<Route path="/home" component={HomePage} />
</Switch>
</BrowserRouter>
</Provider>
This is ActionCreator for redux
.then((res) => res.json())
.then((res) => {
localStorage.setItem('user' , JSON.stringify(res.user));
localStorage.setItem('token' , res.token);
dispatch({type : ActionTypes.SIGN_UP_USER , payload : res.user})
})
.catch((err) => {
dispatch({type : ActionTypes.SIGN_UP_FAILED , payload : err.message})
});
User Reducer :
switch (actions.type) {
case ActionTypes.SIGN_UP_USER:
return {
user: actions.payload, isLoading: false, isError: null
}
signup page
const signupUser = useSelector(state => state.signUpUser);
const {isLoading , user , isError} = signupUser;
useEffect(()=>{
if(user)
history.push(`/home`);
} , []);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(signUpUser(userName , email , password))
}
and configure store file :
const user = localStorage.getItem('user') || null;
{console.log(user)}
const intialState = {
signUpUser : {user}
}
export const configureStore = () =>{
const store = createStore(
combineReducers({
signUpUser : signUpUser
}), intialState , applyMiddleware(thunk , logger)
);
return store;
}
I am following https://github.com/basir/node-react-ecommerce this repository , doing almost same as this but still not working.
Upvotes: 0
Views: 116
Reputation: 4518
Try adding the user
to the dependencies of the useEffect on your signup page list like this:
const signupUser = useSelector(state => state.const {isLoading , user , isError} = signupUser;
useEffect(()=>{
if(user) history.push(`/home`);
}, [user]);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(signUpUser(userName , email , password))
}
the useEffect would basically run the first time (and check if the user exists), and then run again every time the user changes.
If you put an empty array as the dependency list, the useEffect would only run once when the component is mounted.
Upvotes: 2