Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 2.

    PHP

    Top 6 Features of PHP 7.4 – Explained with Examples

    Programming

    23. Уроки Node.js. Домены, “асинхронный try..catch”. Часть 3.

    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
    Thursday, September 11
    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 9: Homework Lesson 8
    JavaScript

    React Lesson 9: Homework Lesson 8

    Mohammad Shad MirzaBy Mohammad Shad MirzaFebruary 24, 2020No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Lesson 9: Homework Lesson 8
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    React Lessons. Lesson 9. Homework Lesson 8
    React Lessons. Lesson 9. Homework Lesson 8

    Hey everyone! Today, we will start our lesson with your home task and do it together. Our main goal here is to learn how to keep data: either in store or in the local state of the components. So, let us discuss it now.

    Theoretically, the store should contain all information needed to describe your app, which means that your state components are empty, but in practice, it is different and there is no sense to move some elements from state to store.

    For example, while working with forms, every change in clicks gets registered in the state, which is not something we would want. Working with standard apps, you should keep in store only the data that will be enough for the full restoration of your app. It gives an understanding of what can be sacrificed when writing an app. For instance, if a user reloads a page and a calendar gets closed, which is not that important, it can be added to the state.

    The things you won’t regret to lose should be stored in the local state. For example, the number of articles is important, which means if some articles are deleted, you need to know this. And you need to knows this even when the page reloads– so, it should be kept in the store.

    Now, we’ve come to an issue of filters and their creation. Let us make a reducer that will store filter values. Right now, all our information is stored in the ArticleList component, and we will separate it into an independent component/container.

    Separation of concerns

    We want our filter feature separate in a container. We want functionality associated with Select and DayPicker currently present in ArticleList in a separate container.

    Let’s get back to our agenda for this lesson and think about the state. Filter info like “from” and “to” constraints are needed to filter out articles that are present in the Redux store. This means that we will have to access the Redux store to filter articles. We would want to know which articles we filtered even when the app reloads. So based on these facts, storing filter information in Redux is better in our case. Let’s code:

    Read More:  Agile Software Development, Scrum part 1

    Step 1: Create filters.js reducer

    Let’s add an action type inside types.js

    // types.js
    
    //...
    export const CHANGE_FILTERS = "change_filters";

    Now, create a file filters.js inside reducers directory

    //import action type
    import { CHANGE_FILTERS } from "../types";
    
    // define initial state which we used in ArticleList component
    const INITIAL_STATE = {
      selectedArticles: null,
      from: null,
      to: null
    };
    
    // define reducer function
    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case CHANGE_FILTERS:
          return { ...state, ...action.payload };
    
        default:
          return state;
      }
    };

    Finally, import this reducer inside /reducers/index.js

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

    Step 2: Create filters.js action

    We have to pass id when we dispatch an action to the reducer. Let’s write an action for that:

    import { DELETE_ARTICLE } from "../types";
    
    export const deleteArticle = id => {
      return {
        type: DELETE_ARTICLE,
        payload: id
      };
    };

    Step 3: Create a View and connect with the store

    Let us create Filters.js in the Containers folder. We will add everything we need for filters right here:

    // container/Filters.js
    
    import React, { Component } from "react";
    import Select from "react-select";
    import DayPicker, { DateUtils } from "react-day-picker";
    import "react-day-picker/lib/style.css";
    
    //import connect and action
    import { connect } from "react-redux";
    import { changeFilters } from "../actions";
    
    class Filters extends Component {
      handleSelectChange = selectedArticles => {
        const { changeFilters } = this.props;
    
        // pass selected article id to action
        changeFilters({
          selectedArticles
        });
      };
    
      getRangeTitle() {
        // use values from props instead of state
        const { from, to } = this.props.filters;
        return (
          <p>
            {!from && !to && "Please select the first day."}
            {from && !to && "Please select the last day."}
            {from &&
              to &&
              `Selected from ${from.toLocaleDateString()} to
                    ${to.toLocaleDateString()}`}{" "}
            {from && to && (
              <button className="link" onClick={this.handleResetClick}>
                Reset
              </button>
            )}
          </p>
        );
      }
    
      handleDayClick = day => {
        const { filters, changeFilters } = this.props;
        const range = DateUtils.addDayToRange(day, filters);
        changeFilters(range);
      };
    
      handleResetClick = () => {
        const { changeFilters } = this.props;
        changeFilters({ from: undefined, to: undefined });
      };
    
      render() {
        const { articles, filters } = this.props;
        // import from filter prop instead of local state 
        const { from, to, selectedArticles } = filters;
        const modifiers = { start: from, end: to };
        const options = articles.map(article => ({
          label: article.title,
          value: article.id
        }));
        return (
          <div>
            {this.getRangeTitle()}
            <Select
              options={options}
              isMulti={true}
              value={selectedArticles}
              onChange={this.handleSelectChange}
            />
            <DayPicker
              className="Selectable"
              selectedDays={{ from, to }}
              modifiers={modifiers}
              onDayClick={this.handleDayClick}
            />
          </div>
        );
      }
    }
    
    const mapStateToProps = state => {
      return {
        articles: state.article.articles,
        filters: state.filters
      };
    };
    
    export default connect(
      mapStateToProps,
      {
        changeFilters
      }
    )(Filters);

    Here, we are using articles and filters from reducer with the help of mapStateToProps argument of connect function.

    Read More:  Implementing Two-Factor Authentication with NodeJS and otplib

    We have extracted filter info associated with Select and DayPicker in a separate file Filter.js. Let’s import this Filter inside ArticleList:

    import React, { Component } from "react";
    import Article from "./Article";
    import oneOpen from "../decorators/oneOpen";
    
    //import Filters
    import Filters from "../containers/Filters";
    
    class ArticleList extends Component {
      renderListItem = () => {
        const { articles, isItemOpen, toggleOpenItem } = this.props;
        return articles.map(article => (
          <li key={article.id}>
            <Article
              article={article}
              isOpen={isItemOpen(article.id)}
              openArticle={toggleOpenItem(article.id)}
            />
          </li>
        ));
      };
    
      render() {
        return (
          <div>
            <h1>Article list</h1>
            <Filters /> // replace old DayPicker component with Filter
            <ul>{this.renderListItem()}</ul>
          </div>
        );
      }
    }
    
    export default oneOpen(ArticleList);

    Our ArticleList component looks much more organized and readable now. Yay 🎉

    So, in this way, we can store the article’s data and filter information separately. Whenever we need it, we take information from both sources – filters and articles – and filter it. As we have filter separated, it works even when we get new articles in the app, the old filter will continue to work until we intentionally change it.

    You can visit this codesandbox below to see today’s lesson in action.


    Edit React_lesson_lesson9

    Your home task code can be found here.

    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
    B2B Leads December 19, 2024

    Effective Strategies for Targeting B2B Lead Generation Audiences

    Targeting B2B lead generation effectively requires a mix of strategic approaches. Focus on defining your ideal customer profile, utilizing data-driven insights, and leveraging social media platforms to connect with decision-makers in your industry.

    Spring Cloud Config Refresh Strategies

    September 11, 2020

    Mastering JavaScript Proxies: Practical Use Cases and Real-World Applications

    May 7, 2023

    Powerful, Opinionated And Idiosyncratic Scripting Language Or What We Know About Python

    April 21, 2020

    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

    How And When To Debounce And Throttle In React

    JavaScript May 14, 2023

    Advanced Node.Js: A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js

    JavaScript January 24, 2020

    Java Stream API

    Beginners October 30, 2020

    WordPress for Non-Programmers: Introduction to the Web Development World

    Beginners August 7, 2019

    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
    Remote Job

    7 Statistics About Remote Work to Make Your Company Better

    Beginners

    Build Real-world React Native App #0: Overview & Requirement

    JavaScript

    Analyzing Leadership Styles and Their Influence on Project Success

    Most Popular

    Enhancing Employee Retention: The Critical Role of Recruiters

    Recruitment

    A Roundup Review of the Best Deep Learning Books

    Beginners

    Effective Strategies for Targeting B2B Lead Generation Audiences

    B2B Leads
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

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