4

In the project we are working on, we have a common interface that contains a date. When we added redux to the project we ran into an issue where we get a warning when storing objects which contain dates internally we recieve a warning

A non serialized value was detected in the state...

So we updated our code to convert the dates to strings in the reducer when storing the objects in the store and convert them back to dates in the selector.

...
reducers: {
  itemAdded(state, action) {
    state.items.push(stringfyDates(action.payload))
  }
  ...
}
...
selectItems = (root) => root.slice.items.map(destrigfyDates)

This fixed the issue but we ran into a new problem, when we use the dates in useEffect dependencies the effect is trigger on every render because there is a different date object in each render.

This made us think we might have handled the situation incorrectly.

My question is

  1. Is the pattern we used in order to store dates in the db an antipattern?
  2. What other approaches are there to handling the situation?
  3. Does redux expect the projects using it to store dates in string format and parse them only when the date properties are needed?
2
  • When storing date, you should always prefer the timestamp (date.getTime()).
    – Ji aSH
    Jan 26, 2023 at 8:26
  • @JiaSH any source or explanation on why this format should be prefered?
    – Plargato
    Jan 26, 2023 at 21:09

1 Answer 1

1

Don't convert them in the selector, you can use the value you got from state directly as a dependency for useEffects as timestamp then you can do whatever you want with it. Don't use the created object as a dependency for useEffect but instead a timestamp or a date as string, object have different references even if they have same value

Comparing objects is not the same as comparing numbers or strings, Objects are compared by reference not by values

And it's a Redux best practice to not store non-serializable values in the state . Values like

  • Promises
  • class instances
  • Dates
  • ...

Check this https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions

2
  • 2
    I understand why the effect triggers on every render, but i dont how we should handle this sitatuation, do you suggest storing the dates as ISO strings in the store and making wide app refactor in order to only convert them to dates if the actual usage requires?
    – Plargato
    Jan 26, 2023 at 21:08
  • I guess so! It's seems a good idea to keep them as ISO strings or timestamps until they really need to be transformed into Date inside the component. In this way they will be better handled inside useEffects and reducers. Oct 31, 2023 at 14:17

Your Answer

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

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