1

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
  • You can also check out github.com/engineforce/ImmutableAssign, which supports immutability and allows you to continue working with POJO (Plain Old JavaScript Object). Commented Jun 21, 2016 at 14:30

1 Answer 1

12

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:

  1. Fetch items from the server as a JSON array of objects
  2. Convert that JSON array to an immutable vector of immutable records
  3. Pass that immutable vector to your components to render them
  4. When editing/creating new items, make sure you only deal with immutable records (that is, keep an immutable newItem record on this.state in the component, and update that record when form fields change).
  5. When the user hit Save, send this.state.newItem to the store, which adds the item to its immutable vector and also converts it to JSON and sends it to the server.
Sign up to request clarification or add additional context in comments.

1 Comment

Clear explanation! I hope someone can also refer to some example code using this way of react to render a form with the use of immutable.js as so far I only see stand alone code from immutable.js

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.