리액트/코드
[리액트] 쿠키값을 이용해 조작하기
임고미
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. useState, useEffect 를 이용해 컨트롤 해준다.
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는 false, true일때는 cookieValue가 true 가 출력될꺼라고 예상했다.
console 값 : 엉망진창..
최초 출력(true)에선 멀쩡하게 들어오나, 값이 바뀌고 나서는 false가 아닌 true 가 한번 더 출력,
그리고 다시 값이 바뀌면 한박자 느리게 false가 출력되는것이었다.
이유는 setState값이 완전히 들어오기 전?에 값을 출력하기때문에
실제로는 false로 바뀌었더라도 console창에는 true가 출력되는것이었다..
♥2. 제대로된 값을 출력하기 위해선 ?
다른데서 console을 찍어보면 된다는 답변을 받았다.
- 조언받은 방법은 다른 버튼을 클릭했을떄 값을 출력해보라는 것이었다. 왜 밖에다 찍으면 안되고 다른데를 클릭했을떄 값을 출력해보라고 하셨는지는 아직 잘 모르겠다.. 어려운코딩
728x90
300x250