Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Interview

    Mastering Phone Interviews: Strategies for Success

    Case Studies

    Case Study: How We Helped a Home Services Business Get 3x More Leads in 30 Days

    Java

    Centralize The Configuration of Services With Spring Cloud Config

    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, September 10
    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 / Apollo Client and Local State Management
    JavaScript

    Apollo Client and Local State Management

    Anssam GhezalaBy Anssam GhezalaNovember 4, 2019Updated:December 4, 2019No Comments15 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Apollo Client and Local State Management
    Apollo Client and Local State Management
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Apollo Client and Local State Management
    Apollo Client and Local State Management

    You built a React App using an Apollo client, and you’re wondering how to manage its state. You are faced with many options: Redux, MobX, Context, Hooks… Which one to pick?

    Well, if your app’s data flow does not consist of many local state keys, you could just stick to GraphQL…

    Apollo to manage the local state of you app? Say what…

    You probably already knew about this option when following the Apollo Docs, maybe you’ve even built apps with it. This article aims to give you a little taste of how to use GraphQL queries with an Apollo server to manage the state of your App.

    We’ll implement a simple Library Management System 📚 (LMS) . LMS represents a library that you own containing books.

    Library Management System (LMS)
    Library Management System (LMS)

     Say you want the following functionalities:

    • See all the books in the library, along with their information
    • Add a book with an author to the library

    Guess what, LMS can do all of these! Let’s get started 🔥

    I- Setting up your Apollo server

    We’ll first set up our graph API’s server.

    Apollo Server is a library that helps you build an API using GraphQL. It can connect to any data source, including REST APIs and databases, and integrates with Apollo developer tooling.

    Lucky for us, we don’t have to do it from scratch. For reference, we will be using this CodeSandbox as our GraphQL server.

    Let’s walk over the pre-built to understand what’s happening and how to use it for our app.

    a) Setting up a schema

    In general, a schema is a representation of a plan or theory in the form of an outline or model. In our case, it represents a blueprint representing the data that flows through the app. With it we can:

    1- Define the data and its type. 

    type Query {
      id: Int
      groceries: {
        product: String
      }
    }

    With this schema, if we make a query as such:

    query {
      id
      groceries: {
        product
      }
    }

    We can get an output of the following format:

    {
      "data": {
        "id" : 1,
     "groceries": [
           {
             "product": "Banana"
           },
           {
             "product": "Broccoli"
           }
         ]
       }
    }

    In our case, we have a library that manages books. Each book has:

    • A unique id
    • A title of type String
    • An author representing a person with a name and email
    • A synopsis of type String

    You can see here that we can define two data types: type Book with id, author, title, synopsis, and type Author with a name and email.

    type Book { 
     id: ID!
     title: String!
     author: Author!
     synopsis: String!
    },
    type Author {
     name: String!
     email: String!
    }

    Note: The exclamation point specifies that such key in the query will never be null. For instance, id: ID! in our Book type means that our server will never return a null value for the id of an object of type Book.

    2) Define queries

    Most types in your schema will just be normal object types, like Book and Author above. But there are two types that are special within a schema:

    • Queries

    Every GraphQL service has a query type and may or may not have a mutation type. These types are the same as a regular object type, but they are special because they define the entry point of every GraphQL query.

    Remember, with our LMS we can see all the books in the library, along with their information. So we need to be able to fetch data from our graph. For that, we use the books key to query an array [Book], meaning an array of objects of type Book.

    type Query {
        books: [Book]
      }
    • Mutations

    A Query lets you fetch data from your server. What if we want to create, delete or update that data? To do so, we use mutations.

    Remember, our LMS gives us the ability to:

    • see all the books in the library, along with their information,
    • add a book with an author to the library,
    • delete a book from the library.

    Notice the last two requirements require data updates? These requirements represent our mutations! So we define the following:

    # The mutation root type, used to define all mutations
     type Mutation {
       # A mutation to add a new channel to the list of channels
       addBook(book: BookInput!): Book
     }

    add(...) takes some book we wish to add to the library as an argument and returns an object of type Book (the newly added book).

    STOP! Where is BookInput coming from?!

    Nice catch! 🔥 Basically in a mutation, you can pass objects with normal types such as strings, ints, enums… Or more complex objects. In our case here, we want to make some updates on the Books in the library by creating a new Book. So we define an input type BookInput that can be passed to our addBook(...) mutation to create a new object.

    Since BookInput follows the format of Book, it also contains an Author object, which we will define as an input type AuthorInput. We get the following input types.

    input BookInput {
      title: String
      author: AuthorInput
      synopsis: String
    }
    
    input AuthorInput {
      name: String
      email: String
    }

    And we’re done with our schema! We put all of our types in our typeDefs constant to get the following:

    // Construct a schema, using GraphQL schema language
    const typeDefs = gql`
      type Query {
        books: [Book]
        book(id: ID!): Book
      }
      type Book {
        id: ID!
        title: String!
        author: Author!
        synopsis: String
      }
      input BookInput {
        title: String
        author: AuthorInput
        synopsis: String
      }
      input AuthorInput {
        name: String
        email: String
      }
      type Author {
        name: String
        email: String
      }
    
      # The mutation root type, used to define all mutations
      type Mutation {
        # A mutation to add a new channel to the list of channels
        addBook(book: BookInput!): Book
      }
    `;

    … Hooray! ✨

    Now let’s do one last little step which is to add some default data to our server:

    const author = { name: "Anssam", email: "a@g.com" };
    const books = [
      {
        title: "Book1",
        id: 1,
        author: author,
        synopsis: "It's a mystery book!"
      }
    ];

    Now we’re finally done with our schema!

    b) Setting up our resolvers

    Now that we’ve defined the data that we’ll manipulate in our app, we need to think of the logic on how to do that, as in, the queries.

    Resolvers provide the instructions for turning a GraphQL operation (a query, mutation, or subscription) into data. They either return the same type of data we specify in our schema or a promise for that data. –Apollo Docs

    In our app we wish to:

    • See all books
    • Add a book to the library

    So we can define a fetching Query for the first two requirements as such:

    const resolvers = {
     Query: {
      books: () => books
     },
    ...
    };

    What does this lead to? Remember, you can use your Apollo Server by hitting the play button on this CodeSandbox that you have now populated with our code. Let’s test our books query to see if it returns all the books we currently own.

    Query all the books in the library
    Query all the books in the library

    Yey it works! ✨

    Now let’s write our mutation to update the data:

    const resolvers = {
      ...
      Mutation: {
        addBook: (root, { book }) => {
          var id = require("crypto")
            .randomBytes(10)
            .toString("hex");
          const newBook = {
            ...book,
            id: id
          };
          books.push(newBook);
          return newBook;
        }
      }
    };

    In our Mutation, we generate a random id to assign to the new book newBook we wish to add. Make sure that you add it to yours books array by doing books.push(newBook)! Let’s test it.

    Mutation
    Mutation

    We have properly added Seif’s book to our library! You can even check by making another Query to get all the books to see that our books array now contains this new addition.

    And we’re done configuring our Apollo server! ✨

    Now let’s move on to the User Interface of our LMS 🔥

    II- User interface

    Let’s now make a UI for our library! For this part, we can use a React CodeSandBox

    a) Setting up our client

    Now that we’re done with building our Apollo server, let’s set up our Apollo client which will fetch data from it.

    We first import ApolloClient…

    import ApolloClient from “apollo-boost”;

    …then we pass the uri of our server to the client, as in, the uri of the server we’ve built in Part I!

    const client = new ApolloClient({
      uri: "https://75183.sse.codesandbox.io/"
    });

    We also import AppolloProvider…

    import { ApolloProvider } from “react-apollo”;

    …then wrap the root our App with it

    function App() {
      return (
        <ApolloProvider client={client}>
          <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
          </div>
        </ApolloProvider>
      );
    }

    What does the ApolloProvider do? If you are already familiar with React’s Context API, it acts just like it: it wraps all the elements that will need access to the client, as in, all the elements that perform queries to the server.

    b) Building our Library component

    Our Library component is the component that will make our queries.

    For now, let’s just build a static component with some styles. It’s really up to you how you want to build it.

    • LMS gives us the ability to add a book to our library: You can add some input fields for each book information (title, author name, author email, synopsis). You can wrap all these inputs in a form to submit to the server.
    • LMS lets us see all the books in the library: You can display your books as a list of using <li> elements, or you can make a <table> element with all your books in it.

    We will use a list of inputs to prompt the user to add a book to the library as follows:

    function Library() {
      let titleInput;
      let authorEmailInput;
      let authorNameInput;
      let synopsisInput;
    …
      return (
          <div className="inputContainer">
            <input
              placeholder="Book Title"
              ref={node => {
                titleInput = node;
              }}
            />
            <input
              placeholder="Book Synopsis"
              ref={node => {
                synopsisInput = node;
              }}
            />
            <input
              placeholder="Author Name"
              ref={node => {
                authorNameInput = node;
              }}
            />
            <input
              placeholder="Auhtor Email"
              ref={node => {
                authorEmailInput = node;
              }}
            />
            <button/>
            >
              Add Book
            </button>
          </div>
      );
    }
    

    Note: Our “Add Book” button does not do anything for now. We will implement the logic of adding a book by using an onClick listener to this button later.

    And we’ll use a table to display our data. It will have the following properties:

    • 3 columns for the book’s title, author name, and synopsis
    • 1 row for each book.

    Note: As we’ve seen in part I, we know that once we’ve perform a query to fetch all the books, we will get a result of the format: data = {books: [{title:"", author:{}, synopsis:""}]}. Our component does not have any data so we have an empty <tbody> for now:

    function Library() {
    …
      return (
    …
          <div className="inputContainer">
            <table>
              <thead>
                <tr>
                  <th>Title</th>
                  <th>Author</th>
                  <th>Synopsis</th>
                </tr>
              </thead>
              <tbody>
              </tbody>
            </table>
          </div>
      );
    }
    

    c) Using Hooks to query data

    Now let’s make our component do something!

    Remember, we know LMS lets us add books and view our books. Both of these requirements have been translated into queries in Part I. All we have to do is call these queries.

    1) Populate our data constant with all the books in our library: You can guess here that we will be using the books query to get all the books

    2) Add some logic to our submitBook function so that it adds a book to our library: You can guess here that we will be using the mutation addBook to add a book to our library

    To do that, we will use gql, useQuery for 1) and useMutation hooks for 2).

    import { gql } from “apollo-boost”;
    import { useQuery, useMutation } from “@apollo/react-hooks”;

    1) We define a GET_BOOKS query as such:

    const GET_BOOKS = gql`
      {
        books {
          title
          author {
            name
            email
          }
          synopsis
        }
      }
    `;
    

    Then use the useQuery hook to submit this query to our server from our Library component:

    const { loading, error, data } = useQuery(GET_BOOKS);
     
    if (loading) return <p>Loading ...</p>;
    if (error) return <p>Error :(</p>;
    

    And we populate our table’s body without fetched data as such:

    function Library() {
      …
      <tbody>
        {data.books.map((book, idx) => (
            <tr key={idx}>
              <td>{book.title}</td>
              <td>{book.author.name}</td>
              <td>{book.synopsis}</td>
             </tr>
         ))}
      </tbody>
      …
    }
    

    Now the table properly displays all the books you currently own in your library. Remember from Part I how we added a default book in our library? You can see it in our table!

    Display books in our table
    Display books in our table

    2) We define a ADD_BOOK mutation as such:

    const ADD_BOOK = gql`
      mutation AddBook(
        $title: String!
        $synopsis: String!
        $authorName: String!
        $authorEmail: String!
      ) {
        addBook(
          book: {
            title: $title
            author: { name: $authorName, email: $authorEmail }
            synopsis: $synopsis
          }
        ) {
          id
          title
          synopsis
          author {
            name
            email
          }
        }
      }
    `;
    

    The mutation takes as parameters :

    • the title of the book as a string,
    • the author’s name as a string,
    • the author’s email as a string,
    • the book’s synopsis as a string,

    … and returns a book object with the same parameters in addition to its id (as in, an object of type Book like we defined in Part I)

    We will call this mutation from our Library component as such:

    function Library() {
      const [addBook] = useMutation(ADD_BOOK)
    }
    

    Then add the onClick listener to our “Add Book” button to call our addBook mutation:

    addBook({
      variables: {
        title: titleInput.value,
        authorName: authorNameInput.value,
        authorEmail: authorEmailInput.value,
        synopsis: synopsisInput.value
      }
    })
    

    Note: We wrap all of our arguments to the addBook call in a variables object so that GraphQL properly maps the arguments to the parameters we defined earlier. Our variables here represent the data of the book we wish to add in our Library

    And now we can add a book to our library!

    Adding a new book requires a refresh to see it in the table
    Adding a new book requires a refresh to see it in the table

    ⚠️ Notice though that we have to refresh the page to see the new addition

    When you execute a mutation, you modify back-end data. If that data is also present in your Apollo Client cache, you might need to update your cache to reflect the result of the mutation. –Apollo Docs

    Luckily, we can add an update function to our useMutation hook to show us the updates of the data, as in, the newly added book.

    const [addBook] = useMutation(ADD_BOOK, {
        update(
          cache,
          {
            data: { addBook }
          }
        ) {
          const { books } = cache.readQuery({ query: GET_BOOKS });
          cache.writeQuery({
            query: GET_BOOKS,
            data: { books: books.concat([addBook]) }
          });
        }
    });

    Let’s look at our update function:

    • We passed in our function the cache object representing the Apollo Client cache. This objects gives us access to the readQuery and writeQuery functions.

    What’s up with readQuery? readQuery is a function in which we pass in an object {query: …}. In that object, we can add a query to the query property. When we do cache.readQuery({query: GET_BOOKS}), we are querying all the books in the library currently stored in the cache.

    What about writeQuery? writeQuery is a function in which we pass an object {query: ..., data: ...}. In that object, we add a query to the query property and some data to the data property. The function writes some data in the shape of the provided GraphQL query. cache.writeQuery({query: GE_BOOKS, data: {books.concat([addBook]}}) writes the newly added book from our mutation to our list of books in our cache. So our cache will have a new data object with all our books + the newly added book.

    • We also pass an object containing data:{addBook}, as in, the return of our addBook mutation (which is an object of type Book).

    Let’s see if our cache is properly being updated after each mutation call (after adding a book)

    Adding a new book without refreshing
    Adding a new book without refreshing

    Works like a gem! 💎

    Checkout your awesome Library Management System 📚 🔥

    Conclusion

    As you can see, setting up our Apollo Client gives us another alternative to managing the state of our application, while giving us some perks:

    • Our server is strongly typed
    • Our server is the only source of truth when it comes to handling the data flow of our app: no need for a separate Redux or MobX store
    • React Hooks with Apollo provide an even easier way to query the data from the server and update it
    • Apollo lets you use your cache in a smart way to dramatically improve the speed of your queries

    This makes local state management with Apollo another good alternative to think about when building your next cool application!

    Notice: I hope this article was helpful, or that you gained something from it! My brothers and I are learning more about React and publish articles on a monthly basis. Follow me on twitter @anssam_ghezala to get in touch! 🙂

    Read More:  Mapping the World: Creating Beautiful Maps and Populating them with Data using D3.js 
    JavaScript react web developer web-development
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Anssam Ghezala

      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
      LinkedIn December 1, 2024

      Maximizing LinkedIn: Strategic Lead Generation for Real Estate

      Maximizing LinkedIn for strategic lead generation in real estate requires a focused approach: optimize your profile, engage with relevant content, and leverage targeted connections. By cultivating meaningful relationships, professionals can enhance their market reach and visibility.

      How to setup SonarQube in a project on Local Machine.

      April 30, 2023

      Fames Acturpis Egestas Sed Tempus Etpharetra Pharetra

      January 28, 2020

      React Hooks + RxJS or How React Is Meant to Be

      July 31, 2019

      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

      3. Уроки Express.js. Шаблонизация с EJS: Layout, Block, Partials

      Programming December 16, 2016

      Best Background Check Services Assessments

      Consultation April 12, 2019

      Imperative Guide to CSS masking

      CSS January 19, 2023

      Exploring Retargeting Ads in B2B Lead Generation Strategies

      B2B Leads December 16, 2024

      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
      Development

      Integrating Data Privacy into Effective Software Development

      Node.js

      Create simple POS with React.js, Node.js, and MongoDB #12 : Getting started with React Table

      Beginners

      Think Like a Pythonista — Building a Book Sharing App

      Most Popular

      Basic Prototype Design

      Beginners

      Strategic Approaches to Navigating Entrepreneurship Competition

      Entrepreneurship

      React Lesson 15: Checking Homework progress from Lesson 14

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

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