Trigger when a cookie changes on client's browser? - React JS

10.4k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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'

import Cookies from "js-cookie";

function App({children}) {
  const [authToken, setAuthToken] = useState(Cookies.get("presence"));
  useEffect(() => {
    // your useEffect code 
  }, [authToken]);


  // Update token with every render when its value has changed.
  const presenceCookie = Cookies.get("presence");
  if (authToken !== presenceCookie ) {
    setAuthToken(presenceCookie);
  }

  return (
    <div>
      {children}
    </div>
  );
}

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.

0
On

setCookie don't have a callback function so that you cant get cookie change in same function. You can use the following code.

const [cookies, setCookie, removeCookie] = useCookies(['presence']);
const [data, setData]=useState();

  useEffect(()=>{

    setCookie("presence","test");
    setData({"presence":"test"})
  },[])

  useEffect(()=>{
    console.log("cookies changed");
  },[data])

Just use data state in your current hook.