'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 1:[1]

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.

Solution 2:[2]

if you need redux solution you can modify your inital state's property to object and add expiration property like this.

const initialState = {
    someProperty: {
        value: '',
        expirationDate: ''
    }
}

and on action dispatch you can pass object with both property value and exp. date like

dispatch({
    type: 'ADD_FOO',
    payload: {
        value: 'bar',
        expirationDate: 1000 //ms (1sec) 
    }
})

and in your reducer you can just

 if(action.type === 'ADD_FOO'){
     return ...state, someProperty: action.payload 
 }

and finally when you need to check expiration you need to check every time you will fetch this data from store if expiration date is more than date.now like this: new Date(someProperty.expirationDate).getTime() < Date.now(), and dispatch new action which deletes this property, or you can add third property to someProperty (in initialState) called expired: false and dispatch action to change expired from false to true. this approach is hard to maintain and you will probably get some bug so i would choose cookie approach.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2