2

I wish to use the value returned from this function:

const quantity = () => {
    let cookies = document.cookie.split("?");
    return cookies.length;
}

in my react component:

const cart_button = (
    <Mfont>{quantity}</Mfont>
);

<Mfont> is a standard span element styled with styled-components;

console.log(cookies.length)

gives me a number based on its length as expected, but I can't figure out how to insert it to my component and update every time a cookie.length increases.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • React components only update when their `props` or `state` changes. So you need to either supply this `quantity` to the component as props, or store it in the state. I can't say any more without seeing the rest of your component(s). – Robin Zigmond Jun 12 '19 at 19:09

2 Answers2

2

According to this answer, the most reliable way still in 2019 to detect changes in cookies is to check document.cookie on interval.

In React 16.8, we have useEffect hook that we could use together with useState hook to run a function on interval and cause the component to update when the value of document.cookie has been updated, like

import React, { useState, useEffect } from 'react';

const MyComponent = props => {
  const [latestCookie, setLatestCookie] = useState(document.cookie);

  useEffect(() => {
    const detectCookieUpdate = document.cookie !== latestCookie && setLatestCookie(document.cookie);
    const interval = window.setInterval(detectCookieUpdate, 1000);

    return () => window.clearInterval(interval);
  });

  return (
    <Mfont>{quantity()}</Mfont>
  );
};

This way we run a function every 1 second that checks if the value of document.cookie is equal to the previous value. Since the value is always a string, it's safe to use strict comparison operator === and not do any checks on top of that. When the values don't match, we run setLatestCookie provided by the state hook, causing the component to render again, and therefore making use of quantity function that will run again.

NoBrainer
  • 5,853
  • 1
  • 27
  • 27
rishat
  • 8,206
  • 4
  • 44
  • 69
0

Have you tried to pass length value as props to your component? Then you can assign that value to the component state. When state changes do whatever you want.