Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Recruitment

    Leveraging Video Recruiting to Attract Top Talent Effectively

    JavaScript

    TOP 5 Books about Silicon Valley that Blew Up the Internet

    Recruitment

    Unlocking Organizational Growth: The Crucial Role of Recruitment

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, January 21
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React / React Lessons / React Lesson 11. Pt.1: Normalize Comments with Immutable.js
    JavaScript

    React Lesson 11. Pt.1: Normalize Comments with Immutable.js

    Mohammad Shad MirzaBy Mohammad Shad MirzaMarch 20, 2020Updated:June 23, 2020No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Lesson 11. Pt.1: Normalize Comments with Immutable.js
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    React Lessons. Lesson 11. Pt.1. Normalize Comments with Immutable.js
    React Lessons. Lesson 11. Pt.1. Normalize Comments with Immutable.js

    In the last lesson, we learned how to use Immutable.js to normalize our articles. Today we are going to do the same with comments.

    In the last article, when we passed the normalized form of an article list, we were passing an id instead of an actual comment. You can see this by opening any comment.

    To make them visible, we need to create a separate reducer responsible for comments and take the needed comments from there. Just like what we’ve done to the articles, we need to do the same with our comments. Let’s start.

    Step 1: Create a comments.js reducer inside a reducers directory

    Let’s recall what we did in the previous lesson. We used normalisedArticle with Record from Immutable.js to create an OrderedMap. Then we used it inside a reducer. We are going to do the same with the comments. But first, let’s extract out the reduce function we used earlier in a separate file. It’s always a good idea to reuse code wherever possible.

    //reducers/utils.js
    import { OrderedMap } from "immutable";
    
    export function recordsFromArray(RecordType, array) {
      return array.reduce((acc, el) => {
        return acc.set(el.id, new RecordType(el));
      }, new OrderedMap({}));
    }

    Then the articles.js reducer will change like this:

    //... imports
    import { recordsFromArray } from "./utils";
    
    const Article = Record({
      id: "",
      date: "",
      title: "",
      text: "",
      comments: []
    });
    
    const defaultArticles = recordsFromArray(Article, normalizedArticles);

    Looks good. Let’s move on and create comments.js reducer.

    //reducers/comments.js
    
    import {} from "../types";
    import { normalizedComments } from "../fixtures";
    import { Record } from "immutable";
    import { recordsFromArray } from "./utils";
    
    // define comment structure
    const Comment = Record({
      id: null,
      user: "",
      text: ""
    });
    
    //create OrderedMap of comments
    const defaultComments = recordsFromArray(Comment, normalizedComments);
    
    // define initial comments
    const INITIAL_STATE = {
      comments: defaultComments
    };
    
    // define reducer to return comments
    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        default:
          return state;
      }
    };

    Step 2: Combine comments.js reducer with store

    Now let’s combine this reducer with others in reducers/index.js

    import { combineReducers } from "redux";
    import article from "./articles";
    import counter from "./counter";
    import filters from "./filters";
    //import comments reducer
    import comments from "./comments";
    
    export default combineReducers({
      article,
      counter,
      filters,
      comments
    });

    Step 3: Update usage

    We are using the CommentList.js component to render a list of comments. Let’s connect it with the store and render the normalized comments. Go to components/CommentList.js.

    Read More:  Handling GraphQL API Authentication using Auth0 with Hasura Actions

    Fist, import connect function from “react-redux:“

    //... other imports
    import { connect } from "react-redux";

    Now change the export function and connect it with the store:

    // get comments based on id from store
    const mapStateToProps = (state, props) => {
      console.log({ props, state });
      return {
        commentObj: props.comments.map(id => state.comments.comments.get(id))
      };
    };
    
    //Connect a component with store
    export default connect(
      mapStateToProps,
      {}
    )(toggleOpen(CommentList));

    Note that we are going to use commentObj as props inside component. In mapStateToProps, we will go through the comment array and, using the immutable map, we will extract our comments (i.e. the comment records) out of state according to their ids.

    Let’s update the render function to use commentObj from props as follows:

    const { commentObj, isOpen, toggleOpen } = this.props;
    if (!commentObj || !commentObj.length) return <h3>no comment yet</h3>;
    
    const commentItems = commentObj.map(comment => (
        <li key={comment.id}>
        <Comment comment={comment} />
        </li>
    ));

    And we are done. One of the key benefits of using Immutable.js is that all the operations done on data are immutable by default. This means we can update our filter method inside reducers/articles.js like this:

    case DELETE_ARTICLE:
        return { ...state, articles: state.articles.delete(action.payload) };

    We only describe what article should be deleted from the object. If something needs to be added, you use set(), and for updates, you use update().

    articles.set()
    articles.update()

    You will need it for your home task. Moreover, Immutable.js perfectly works with deep nesting. If you need to update the comments from the article inside the object with all articles, and this object may be inside another object keeping other data, it will be too complicated to write multiple wrapping functions. For such cases Immutable.js has this:

    articles.updateIn([id, 'comments'], comments => ...)

    Let us check. Everything perfectly works!

    Read More:  Navigating Remote Project Management Challenges: Best Practices

    We’ve already normalized the data and stored articles and comments separately. It will be a great advantage when we will read data from API, as quite often REST API returns data in this form. It means endpoints are responsible for some resources – for example, for an article or comment – and you may not have an API that will be ready to give you a tree-like structure of the article with all comments immediately. This problem can be solved by GraphQL, for example. Relay and GraphQL are React structures – the things Facebook uses for data fetching, but these are quite complicated themes. In general, our API will look like:

    http://localhost:8080/api/article

    There will be a separate API for comments:

    http://localhost:8080/api/comment

    And we will need to make them work together. So, it will be our upcoming task, when we’ll get all the articles and comments from the real API.

    Further, we will continue to explore Redux API and see what Middleware is. Everything we’ve previously done used to be perfectly described with pure functions. You should do everything with pure functions in Redux – both action creators and reducers. They receive old data and action at the input and return a new object with new articles at the output, without changing anything outside.

    On the other hand, not everything can be described with pure functions, sometimes we may need side-effects, which can be any access to API, Logging, Reporting, etc. All these are brought to middleware. These are the objects that may be in between the executed dispatch for action and the moment when it came to your reducers.

    Link to the git repository. 

    react react lesson
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Conducting Effective Post-Project Evaluations: A Guide

    December 16, 2024

    Strategies for Keeping Projects on Track and Meeting Deadlines

    December 10, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    SaaS & Tech August 27, 2025

    Maximizing Impact: Strategies for SaaS & Technology Marketing

    To maximize impact in SaaS and technology marketing, focus on targeted messaging, leverage data-driven insights, and foster customer relationships. Emphasizing unique value propositions and seamless user experiences will drive engagement and retention.

    Conquering Imposter Syndrome: Empowering Startup Founders

    December 16, 2024

    Tim&Tom JavaScript Frameworks

    August 24, 2016

    Уроки React. Урок 4. Домашнее Задание.

    September 14, 2016

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Уроки React. Урок 12.

    Programming November 1, 2016

    How to create a Github Jobs app using React, Apollo, and GraphQL – Part #2

    GraphQL October 26, 2020

    Leveraging Interactive Content for Effective B2B Lead Generation

    B2B Leads December 1, 2024

    TOP Most In-Demand IT Certifications 2020

    Beginners January 1, 2020

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Node.js

    Node.js Lesson 12: HTTP Module and Nodemon

    JavaScript

    Libero Enim Sedfaucibus Turpis Magna Fermentum Justoeget

    Programming

    Уроки React. Урок 13. Часть 1.

    Most Popular

    Transforming LinkedIn Connections into Viable Sales Leads

    LinkedIn

    Unlocking Business Success: The Strategic Power of Storytelling

    Entrepreneurship

    Essential Strategies for Securing Startup Funding Effectively

    Entrepreneurship
    © 2026 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.