I'm building a simple React Flux js app similar to TodoList, which basic functionality lies in CRUD operations on some entities. When app starts it fetches the data from server and shows the list of items, then I can create new item using form, edit and delete. I decided to try Immutable.js approach but faced the question: when and which data should I convert to immutable objects. For example when I fetch the list, I make it immutable(Immutable.fromJS()) and then assign to store's state, right? But then I create new item, get plain object from the form fields and should somehow post this data to server. In order to avoid loading the list again I want to add this new item to immutable store list. So how should I deal with such situations when I have to convert some objects to immutable for app use, and fetch and send data to server using plain json?
1 Answer
You want to make all your objects immutable. The only time you convert it to a mutable object is when you need to send it to the server. And since you get back a plain JSON object from the server, you convert that to an immutable object when you fetch it.
When you create a new item, you want an immutable object as well, which you send to the store. So the state of the store is just a bunch of immutable objects inside an immutable vector. The fact that you need to send JSON objects to the server is an implementation detail of the communication with the server, and that should only be known by the store/service that handles the communication.
So the flow would be:
- Fetch items from the server as a JSON array of objects
- Convert that JSON array to an immutable vector of immutable records
- Pass that immutable vector to your components to render them
- When editing/creating new items, make sure you only deal with immutable records (that is, keep an immutable
newItemrecord onthis.statein the component, and update that record when form fields change). - When the user hit Save, send
this.state.newItemto the store, which adds the item to its immutable vector and also converts it to JSON and sends it to the server.