Search code examples
reactjscookiesantd

How to store dates that will expire in an hour in React?


I have an app with datepicker from antd ui library. The question is about keeping data for an hour after it was chosen with datepicker. Please help me to implement this with React.

I wish the browser keep it even if I close tab and finish the session. And it is important that I keep it on the front without server. I know about 3 ways:

  • localstorage,
  • sessionstorage
  • cookies.

Probably sessionstorage is no good. Cookie is ok and localstorage has no expiry mechanism. Cookie is probably has to be set without libs. I think it goes like that

componentDidMount(){
   document.cookie = "rememberDates=true; expires=3600000";
}

Solution

  • There is nothing specific to the React library that's made to help with storing data in the browser, you'll have to use browser APIs for that. Using a cookie is probably your best bet.

    Assuming your date is stored in the Javascript Date object, here's a start to what I would do:

    // saves the date value as a string to a cookie called savedDate
    function writeDateCookie(date) {
      document.cookie = `savedDate=${date.toString()}; max-age=3600`;
    }
    
    // loads the date object from the savedDate cookie
    // returns the date as a string or null if it does not exist
    // can be converted back to date with new Date(dateString)
    function getDateCookie() {
      const cookieObj = Object.fromEntries(
        document.cookie.split("; ").map(c => {
          const [key, ...v] = c.split("=");
          return [key, v.join("=")];
        })
      );
      return cookieObj.savedDate || null;
    }
    

    EDIT

    Since the addition of hooks, there is an easy way to react-ify my original answer. You can easily make a hook to get and set a date cookie using the above functions like so:

    function useDateCookie () {
      const [date, setDate] = useState(() => {
        return getDateCookie();
      });
    
      const updateDate = (value) => {
        setDate(value);
        writeDateCookie(value);
      };
    
      return [date, updateDate];
    }
    

    And you can use it like this:

    const App = () => {
      const [date, setDate] = useDateCookie("")
    
      return <div>My date is: {date.toString()}</div>
    }
    

    Alternatively, you could use a pre-built solution which handles all types of cookies using something like react-use-cookie.