본문 바로가기

STUDY/React

React | id저장하기 (react-cookie)

쿠키에 아이디를 저장하고, 저장되어있을 경우 아이디 입력란에 나타나있도록 하기..

1. install

npm install react-cookie

 

 

react-cookie

Universal cookies for React

www.npmjs.com

 

2. import

import { useCookies } from 'react-cookie';

 

3. 사용예시

 

hooks로 사용할 수 있다.

const [cookies, setCookie, removeCookie] = useCookies(['rememberEmail']);

 

import React, { useState, useEffect } from 'react';
import {useCookies} from 'react-cookie';

const LoginPage = () => {

  const [email, setEmail] = useState("");
  const [isRemember, setIsRemember] = useState(false);
  const [cookies, setCookie, removeCookie] = useCookies(['rememberEmail']);

  useEffect(() => {
      if(cookies.rememberEmail !== undefined) {
        setEmail(cookies.rememberEmail);
        setIsRemember(true);
      }
   }, []);

  const handleOnChange = (e) => {
    setIsRemember(e.target.check);
    if(e.target.check){
      setCookie('rememberEmail', email, {maxAge: 2000});
    } else {
    removeCookie('rememberEmail');
    }
  }

  return(
      <>
      {* 생략 *}
        <label className="loginPage_text">
            <input type="checkbox" onChange={handleOnChange}
            checked={isRemember}
            />
          ID 저장하기
        </label>  
      {* 생략 *}
      </>
    )
  
}

export default LoginPage;

새로고침 후 저장된 모습..