Using Immutable Js

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 {
  id=null;
  name=null;
  constructor(uid,username){
  this.id = uid;
  this.name = 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,
           otherdata:{
                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"));
users.forEach(user=>{
  console.log(user)
})
/** setting users to data **/
data = data.set("users",users);

/** getting length of Immutable List **/
console.log(data.get("users").size)

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 item.id ==3;
})

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

/** 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)=>{
    item.name = "Abhimanyu Rathore"
  return item;
   });
   
 console.log(data.get("currentUser"));

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

console.log(data.get("otherdata").get("loggedin"));


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 item.id == 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(user.id,user.name);
   u.name ="John Doe";
   return u;
  }) )
} else {
cosole.log("user not found");
}

console.log(data.get("users").get(userIndex));   

Looking for more examples ? Please post your queries in comment

Add a Comment

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