Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Redux with models

I've started using Redux with React and I absolutely love it. However, the problem I'm having currently is that besides state, I also have more information I need to store/use throughout my application.

In this specific case I have a model with state that's fetched from an API. This model also has some info about itself, e.g. how you display a property on the screen "name" => "Name of the blabla". I understand how to work with state using Redux, but I'm have trouble seeing what do with this other info that I still need propagated throughout the application but is not actually state.

like image 221
Robin_f Avatar asked Oct 29 '15 08:10

Robin_f


People also ask

Can Redux be used with any framework?

Redux itself is a standalone library that can be used with any UI layer or framework, including React, Angular, Vue, Ember, and vanilla JS.

Can you use Redux with functional components?

Using Hooks in a React Redux App​ From there, you may import any of the listed React Redux hooks APIs and use them within your function components.

Should I use Redux for everything?

As a rule of thumb - and one shared by one of Redux's creators, Dan Abramov - you don't need to use Redux unless you're unable to manage state within React or other front-end frameworks you're working with.


1 Answers

According to Redux, the State is the only "source of truth". And it should not have duplication (which would lead to inconsistencies).

So your state should store the name, but not the computed label property.

Indeed, "Name of the blabla" is a function (in the mathematical sense) of your Name value, and if they differ (for example, if at some point name === 'foo' but the label is 'Name of the bar' instead of 'Name of the foo'), then you have a problem...

So what I would do, is just store the minimum in your state (name in that case), and compute the label directly in the Component, where you need it.

If you need that to be re-used, then create a Component that only does take your name as a prop, and render a string with "Name of the blablaba" (if name = blabla I suppose).

If you need more complex computation (say you have multiple labels, date calculations etc.), you can always create a function that takes your State in input, and spit out your "Model" in output with everything calculated.

Redux is very functional in nature, so you might as well embrace it :)

like image 108
Antoine Jaussoin Avatar answered Sep 20 '22 18:09

Antoine Jaussoin