1

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";
}
5
  • 1
    What's wrong with your cookie approach?
    – James
    Nov 5, 2019 at 16:53
  • I wonder how to read cookie and how to make expiry check mechanism
    – kilogram
    Nov 5, 2019 at 17:00
  • Also I am interested how exprerienced react developers solve this problem. Someone may have used cookie in React spa
    – kilogram
    Nov 5, 2019 at 17:02
  • 1
    @kilogram when you add expiry date it automatically expires. to check if it exists, you just need retrieve cookie and check if exists with simple if else statmenet
    – iLiA
    Nov 5, 2019 at 17:28
  • yeah I read already about checking for cookie existence thanks
    – kilogram
    Nov 5, 2019 at 17:35

2 Answers 2

5

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.

3
  • If this isn't direction you're looking to go, let me know Nov 5, 2019 at 17:32
  • That is an interesting solution. Excellent vanilla js solution
    – kilogram
    Nov 5, 2019 at 17:43
  • 1
    If you just call the getDateCookie function in the componentDidMount lifecycle method and the writeDateCookie function whenever the date is updated, it’s officially reactified Nov 5, 2019 at 17:58
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.

5
  • This is an interesting thing. But it requires dispatching action (fetching). In quiet mode it wont work. App will just stay untouched and unaware of cookie expiry
    – kilogram
    Nov 5, 2019 at 17:47
  • You will have to kick redux machine each time I need to check the cookie
    – kilogram
    Nov 5, 2019 at 17:53
  • you are correct, it will only notice expiration when you fetch data. unfortunately this is only way (as i know) to implement expiration check with redux, as i admitted using cookie is better
    – iLiA
    Nov 5, 2019 at 17:53
  • I appreciate your attempt to use it with redux
    – kilogram
    Nov 5, 2019 at 17:54
  • thank you! hope it helped (to understand it is not the best approach LOL)
    – iLiA
    Nov 5, 2019 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.