When my app mounts, i try to fetch the user by token, that is stored in the local storage. If the token is valid, i then set the user from response to the store. I want for user to see /profile page, only when the user is in the store. But i don't seem to have any idea on how to implement it. If there is no user in the store AND they are on some 'protected' pages like /profile i want to redirect them to login. But the problem is, at the beginning there is no user in the store, so i can't just check for it, and then conditionally redirect(or not) to other pages when the user reloads the page.
App.js:
useEffect(()=> {
dispatch(preserveUser())
}, [dispatch])
User.sagas.js:
export function* handleUserPreserve() {
try {
yield put(resetState());
yield put(setUserLoading(true));
const user = yield call(
getItems,
`query {
getUserByToken {
purchasedProducts
orders
token
_id
email
firstName
}
}`
)
yield put(setUser(user.data.getUserByToken));
yield put(setUserLoading(false));
} catch (error) {
yield put(setUserError(error.message.replace('GraphQL error: ', '')));
yield put(setUserLoading(false));
}
}
export default function* userSaga() {
yield takeEvery(PRESERVE_USER, handleUserPreserve);
}
Initial state:
export const initialState = {
userData: null,
};