Home > Software design >  My user is gone when i refresh page ReactJS NodeJS
My user is gone when i refresh page ReactJS NodeJS

Time:10-22

I am a beginner at React and started making a Full Stack app (a small Blog app with authentication). I use the JWT token that I put in the Cookie when the User Login. I print the name of the logged in user in the header. It does it all perfectly until the page refreshes. When I refresh the page I can still access protected routes because I have a JWT cookie in Storage, but I lose the entire user object, when the user login the object is full of user information and when I refresh the page the object is empty.

This is my React Reducer:

export const userLoginReducer = (state = { user: {} }, action) => {
  switch (action.type) {
    case USER_LOGIN_REQUEST:
      return { loading: true, isAuthenticated: false };
    case USER_LOGIN_SUCCESS:
      return {
        ...state,
        loading: false,
        isAuthenticated: true,
        user: action.payload,
      };
    case USER_LOGIN_FAIL:
      return { loading: false, isAuthenticated: false, error: action.payload };
    case USER_LOGOUT:
      return { loading: false, isAuthenticated: false, user: null };
    default:
      return state;
  }
};

This is my React Action:

const { data } = await API.post(
  '/api/v1/users/login',
  { email, password },
  config
);
 dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
} catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

API is config for Axios:

export default axios.create({
  baseURL: 'http://localhost:8000',
  withCredentials: true,
  credentials: 'include',
});

And this is my Login Screen:

const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const redirect = location.search ? location.search.split('=')[1] : '/';

  const dispatch = useDispatch();

  const userLogin = useSelector(state => state.userLogin);
  const { loading, error, isAuthenticated } = userLogin;

CodePudding user response:

Is user: action.payload the user object?

These data aren't being stored in the cookie so they will not persist after page refresh. You'll want to re-fetch on refresh or store them in a persistent storage such as localStorage and check it before you fetch.

CodePudding user response:

After you dispatch USER_LOGIN_SUCCESS in your Thunk, you can add the user information to local storage:

const { data } = await API.post(
  '/api/v1/users/login',
  { email, password },
  config
);
  dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });

  // Setting user to local storage
  localStorage.setItem('user', JSON.stringify(data));

} catch (error) {...}};

Then in your store.js file (or whatever file you configure your store in), you can get the user object from local storage and add it to the initial state, like so:

const user = localStorage.getItem('user')
  ? JSON.parse(localStorage.getItem('user'))
  : { user: null };

const initialState = {
  // Add the user object from local storage to whatever slice of state is appropriate
  auth: { user, loading: false },
  ...
  };
  • Related