ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 세션 관리 in React
    개발 일지/Front-end 2022. 1. 11. 16:28
    반응형

    안녕하세요?

     

    이번 글에서는 모든 스킬 레벨에서의 개발자들이 고민하는 세션에 대해 생각해 보겠습니다.

     

    여러 블로그들과 포스트들을 참고해 보면 다음과 같습니다.

     

    브라우저의 local storage, session storage 활용하기 및 쿠키 관리, redux-react-session, redux-persist 등등 매우 많은 전략들이 있습니다.

     

    Local Storage와 Session Storage 모두 브라우저에서 제공되는 저장소 인데 둘 모두 동일한 기능을 제공합니다.

    다만 세션 스토리지의 경우 세션이 유지되는 동안에만 데이터가 유지됩니다.

    (여기서 세션은 브라우저 탭이라고 이해하면 됩니다.)


    간단하게 생각해서 세션 데이터는 쿠키로 유지해보도록 하겠습니다.

    필요한 경우 만료기간을 지정할 수 있습니다.

     

    의존성

    React의 Hook 기능을 활용합니다.

    • history
    • react-cookie
    • react-router
    • react-router-dom

    route 구성하기

    먼저 아래와 같이 라우트를 구성합니다.

    import React from "react";
    import { Router, Switch, Route } from "react-router";
    import { createBrowserHistory } from "history";
    
    const Routes = () => {
      return (
        <Router history={history}>
          <div className="navbar">
            <h6 style={{ display: "inline" }}>Nav Bar</h6>
          </div>
          <Switch>
            <Route path="/login" component={LoginHandler} />
            <Route path="/logout" component={LogoutHandler} />
            <Route path="*" component={ProtectedHandler} />
          </Switch>
        </Router>
      );
    };
    
    const App = () => (
      <div className="App">
        <Routes />
      </div>
    );

     

    다음으로, 간단한 라우트 기능을 구성합니다. (로그인, 로그아웃)

    const LoginHandler = () => {
      return (
        <div style={{ marginTop: "1rem" }}>
          <form onSubmit={handleSubmit}>
            <input
              type="email"
              placeholder="Enter email address"
            />
            <input type="submit" value="Login" />
          </form>
        </div>
      );
    };
    
    const LogoutHandler = () => {
      return <div>Logging out!</div>;
    };
    
    const ProtectedHandler = () => {
      return (
        <div>
          <Link to="/logout">Logout here</Link>
        </div>
      );
    };

     

    쿠키 관리하기

    session.js 파일을 생성하고 내부에 다음과 같이 "react-cookie"를 사용해서 메소드를 작성합니다.

    import React from "react";
    import { Cookies } from "react-cookie";
    
    const cookies = new Cookies();
    
    export const setCookie = (name, value, option) => {
        return cookies.set(name, value, { ...option });
    }
    
    export const getCookie = (name) => {
        return cookies.get(name);
    }

     

    로그인 및 로그아웃에 쿠키 적용하기

    우선 로그인에 쿠키를 적용합니다. 

    폼에서 입력받은 이메일을 쿠키에 저장해보겠습니다.

    const LoginHandler = ({ history }) => {
      const [email, setEmail] = useState("");
      const [loading, setLoading] = useState(false);
      const handleSubmit = async e => {
        e.preventDefault();
        setLoading(true);
        // NOTE request to api login here instead of this fake promise
        await new Promise(r => setTimeout(r(), 1000));
        setCookie({ email });
        history.push("/");
        setLoading(false);
      };
    
      if (loading) {
        return <h4>Logging in...</h4>;
      }
    
      return (
        <div style={{ marginTop: "1rem" }}>
          <form onSubmit={handleSubmit}>
            <input
              type="email"
              placeholder="Enter email address"
              value={email}
              onChange={e => setEmail(e.target.value)}
            />
            <input type="submit" value="Login" />
          </form>
        </div>
      );
    };

     

    로그아웃에서는 쿠키값을 삭제하고 로그인 페이지로 이동할 수 있습니다.

    const LogoutHandler = ({ history }) => {
      useEffect(
        () => {
          Cookies.remove("session");
          history.push("/login");
        },
        [history]
      );
    
      return <div>Logging out!</div>;
    };

     

    컨텍스트 구현하기

    이제 세션 데이터를 리액트 컴포넌트에서 사용하기 위해 세션 객체를 리액트 컨텍스트로 구현해 보겠습니다.

     

    아래 코드를 session.js 파일 하단에 추가합니다.

    export const SessionContext = React.createContext(getCookie("session"));

     

    SessionContext를 임포트하고 Router를 감싸줍니다.

      return (
        <SessionContext.Provider value={}>
          <Router history={history}>
            {/* routes */}
          </Router>
        </SessionContext.Provider>
      );

     

    Provider는 value 파라미터를 통해 값을 제공할 수 있습니다.

    const Routes = () => {
      const [session, setSession] = useState(getSessionCookie());
    
      return (
        <SessionContext.Provider value={session}>
          <Router history={history}>
            {/* routes */}
          </Router>
        </SessionContext.Provider>
      );
    };

     

    그리고 마지막으로, 로그인 또는 로그아웃할 때 세션의 상태를 업데이트할 수 있도록 합니다.

    useEffect Hook를 활용하여 작성할 수 있습니다.

    최종적으로 Routes 컴포넌트는 아래와 같습니다.

    const Routes = () => {
      const [session, setSession] = useState(getSessionCookie());
      useEffect(
        () => {
          setSession(getSessionCookie());
        },
        [session]
      );
    
      return (
        <SessionContext.Provider value={session}>
          <Router history={history}>
            {/* routes */}
          </Router>
        </SessionContext.Provider>
      );
    };

     

    컴포넌트에서 컨텍스트 접근하기

    useContext Hook를 사용하여 컨텍스트에 접근합니다.

    SessionContext를 임포트하고 useContext를 호출합니다.

    const session = useContext(SessionContext);
    
    console.log("email : " + session.email);

     

    Reference:

    Handling User Sessions with React Context

     

    Handling User Sessions with React Context

    One of the most fun aspects of starting a new project is getting to work with the latest technologies. This time around we chose to keep React but were finally…

    www.jmfurlott.com

     

    반응형

    '개발 일지 > Front-end' 카테고리의 다른 글

    GitHub pages by Next.js  (0) 2023.08.31
    RTK Query 알아보기 (feat.Redux Toolkit)  (0) 2023.01.13
    Redux Toolkit 들어가기  (0) 2023.01.13
    React 프로젝트 구조 잡기 고민  (0) 2021.12.30
Designed by Tistory.