im going to add a new feature to the existing php site using react js. i want to do something when a specific cookie changed on clients browser side. this cookie is used to authenticate the user in react.
i used both 'react-cookie','js-cookie' libraries to view and create cookies.
how to trigger when a cookie changed on the client's browser side?
I used useEffect but it triggers only when I'm using 'setState' to change the cookie. it is not detected when manually cookie changed on the browser.
const [cookies, setCookie, removeCookie] = useCookies(['presence'])
useEffect(()=>{
setCookie("presence","test");
},[])
useEffect(()=>{
console.log("cookies changed");
},[cookies])
is there any way to achieve this task?
You can update your cookies with every render by checking your "authToken" state value with the current cookie value, if it changed, you update the state variable forcing useEffect to trigger.
Here's an implementation using 'js-cookie'
This way if the token is modified in any way manually or not, and any change happened afterwards that required rerendering the component such as navigation, requesting authorized page, etc., your useeffect logic will run again.