개발공부 임고미

[리액트] 쿠키값을 이용해 조작하기 본문

리액트/코드

[리액트] 쿠키값을 이용해 조작하기

임고미 2020. 9. 2. 11:28
728x90
300x250

document.cookie  이용해서 쿠키를 받아와도 되지만간단히 라리브러리를 통해 통제가능

1. 라이브러리 로드 : universal-cookie

2. src/utils.ts안에

import Cookies, { CookieSetOptions, CookieGetOptions } from 'universal-cookie';

export function getCookies(name: string, options?: CookieGetOptions) {  
	const cookies = new Cookies();  
    return cookies.get(name, options);
}

3. 사용하고자 하는 component  가서,

import { getCookies } from 'lib/utils';

import { getCookies } from 'lib/utils';

4. useStateuseEffect  이용해 컨트롤 해준다.

const [cookies, setCookies] = useState(getCookies('cookie name'));
const [cookieValue, setCookieValue] = useState(true); 

useEffect(() => {
  if (cookies === 'value') {
   // true 의 값
   setCookieValue(false)
  } else {
   //false 의 값
   setCookieValue(true)
  }     
   console.log(cookieValue);
}, [cookies]);

useFffect(() => {
  setCookies(getCookies('cookie name'));
}, [getCookies('cookie name')]); 

5. 완료!

시행착오 

♥1. console은 어디에 찍어야하지?

cookie의 value값에따라 cookieValue을 바꾸고바뀐값을 확인하기 위해 useEffect안에 console.log를 찍었다.

기대값 : false 값일때cookieValue는 falsetrue일때는 cookieValue가 true  출력될꺼라고 예상했다.

console  : 엉망진창..

최초 출력(true)에선 멀쩡하게 들어오나값이 바뀌고 나서는 false가 아닌 true  한번  출력,

그리고 다시 값이 바뀌면 한박자 느리게 false가 출력되는것이었다.

이유는 setState값이 완전히 들어오기 ? 값을 출력하기때문에

실제로는 false로 바뀌었더라도 console창에는 true가 출력되는것이었다..


♥2. 제대로된 값을 출력하기 위해선 ?

다른데서 console을 찍어보면 된다는 답변을 받았다.

조언받은 방법은 다른 버튼을 클릭했을떄 값을 출력해보라는 것이었다 밖에다 찍으면 안되고 다른데를 클릭했을떄 값을 출력해보라고 하셨는지는 아직  모르겠다.. 어려운코딩

728x90
300x250

'리액트 > 코드' 카테고리의 다른 글

[리액트] router 사용하기  (0) 2020.09.08
Comments