Using Immutable Js


Immutable Js is the JavaScript Library which provides immutability to JavaScript Object which is the key ingredient of React data store Management.

However the docs of Immutable Js are kinda confusing one, there are no clear examples of performing the basic operations such as

  • How to add new variable to existing Immutable Object
  • How to Update an existing key  in Immutable List
  • How to Replace the key in immutable Map
  • Searching an immutable JS Map

it took me a while to understand it works, so i decided to blog some basic but key operations which we perform on Immutable Object

   /** Demo Object Class for the Example **/
class Person {
  constructor(uid,username){ = uid; = username;

Creating Immutable Object from Javascript Object or JSON

    var immutable = require('immutable');
    let data = immutable.formJS(
      users: [
               new Person(1,"Dave"),
                   new Person(2,"John")
       currentUser: null,
                loggedin : false

Adding an item to immutable List

adding an item to immutable List
in our case Users key in data map is a List
//data.get("users") provide the users list from data Map
let users = data.get("users");
users = users.push(new Person(3,"Abhimanyu"));
/** setting users to data **/
data = data.set("users",users);

/** getting length of Immutable List **/

Updating key in Immutable map

    /** i am going to set newly added user with id 3 as current user **/

/** searching Immutable List **/
let index  = data.get("users").findIndex(item=>{
  return ==3;

data= data.set("currentUser", data.get("users").get(index));

/** updating the Class Type Object **/
/** update option requires the update callback function in which it passed the current value of item and expects an updated item in return **/

data.update("currentUser",(item)=>{ = "Abhimanyu Rathore"
  return item;

/** updating Non classType key **/
data = data.setIn(["otherdata","loggedin"],true)


Searching and Immutable List and Performing the Update on key

 /** now lets update the user for which we only know the some unique property value, in our case its user id  **/
let userIdToUpdate = 2;

userIndex = data.get("users").findIndex(item=>{
 return == userIdToUpdate;

if(userIndex >=0 ){
    data = data.set("users",data.get("users").update(userIndex,(user)=>{
   /** class objects are not Immutable even with Immutable Js until and unless you Use Records, so use cloneDeep Methods here like $.extend from jquery or cloneDeep from lodash **/
   //i am just creating new object for this demo
   let u = new Person(,; ="John Doe";
   return u;
  }) )
} else {
cosole.log("user not found");


Looking for more examples ? Please post your queries in comment

Add a Comment

Your email address will not be published. Required fields are marked *