Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux state and momentjs

I have several dates in my redux state.

Within my app, I want to manipulate only moment objects.

To achieve this, I added a function that takes my AJAX queries, and momentize all of my dates.

But when I check what I get in the store, I still have a string ("2018-07-10T08:31:09.877Z") which appears to be the JSON.stringify version of my moment object.

How am I supposed to handle this? I am aware I can have listeners on the store, but, this won't add a processing when deserializing the state into an object.

I am surprised I haven't found anything on the web, besides this issue, which is even more specific since it deals with persisting the store.

Cheers

like image 307
Augustin Riedinger Avatar asked Nov 24 '25 11:11

Augustin Riedinger


1 Answers

Redux documentation highly recommends to only put plain serializable objects in the Store.

Because of this, I'm approaching the same case as yours as having a Selector layer, where I'm getting the needed Store data in the proper format and later use the formatted (computed) data in the components.

So here's the flow I can recommend you:

  1. Keep your Store's Dates in UNIX timestamps.
  2. Have a Selector layer, where you will access the Store and convert the UNIX timestamps to Moment objects. You can play with reselect library.
  3. In your components you will get the Store's objects, as calling the selectors.

Can I put functions, promises, or other non-serializable items in my store state?

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store. It's technically possible to insert non-serializable items into the store, but doing so can break the ability to persist and rehydrate the contents of a store, as well as interfere with time-travel debugging.

If you are okay with things like persistence and time-travel debugging potentially not working as intended, then you are totally welcome to put non-serializable items into your Redux store. Ultimately, it's your application, and how you implement it is up to you. As with many other things about Redux, just be sure you understand what tradeoffs are involved.

like image 87
Jordan Enev Avatar answered Nov 27 '25 22:11

Jordan Enev