Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 742
Tiran Avatar asked Jun 15 '26 20:06

Tiran


1 Answers

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.

like image 190
Abdelrahman Avatar answered Jun 21 '26 05:06

Abdelrahman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!