Skip to content
로그인 구현학습 기록

Implementing login in React with cookies and localStorage

1 min readLearningMoved from my Tistory blogRead the Korean original

User controller
Figure 1. User controller

Because I need to run a local server, I'm running the files the back-end developers gave me on my own.

Login
Figure 2. Login

In the login form, I take the email and password as input through UseRef.

The input data, the email and password, is sent to the server with a POST through the async function fetchLoginApi.

If it goes through normally, I use SetCookie on the state from React-cookie to save the token value in a cookie.

Then, with useDispatch and setUser(), I destructure the user info held in action.payload and update the values currently stored in initialState.

js
const userDispatch = useDispatch()

There was a problem when I did only the part above: when the page was refreshed or another page rendered, the user info managed by redux disappeared.

So when calling the setUser function, I also stored the user data, converted to JSON, in localstorage with setItem() under the key 'USER'.

Also, initialState parses and assigns the value fetched from localstorage with getItem('USER') if there is one, and if there isn't, it assigns the value on the right through the nullish coalescing operator.

That way, the user info can be accessed from every page.

  • #Login
  • #localStorage
  • #React
  • #Spring Boot
  • #Cookies
  • #Token

More in Learning