Skip to main content

ReactJS(v18) | Apollo GraphQL Library | JSON GraphQL Server| CRUD Example

In this article, we will understand the Apollo GraphQL library to consume the GraphQL Endpoint in the ReactJS application with a sample CRUD example.

GraphQL API:

GraphQL API mostly has a single endpoint. So data fetching or updating will be carried out by that single endpoint. For posting data or querying data, we have to follow its own syntax. GraphQL carries two essential operations:
  • Query(Fetches Data)
  • Mutation(Saves or Updates Data)

Create ReactJS(v18) Application:

Let's create a ReactJS application to accomplish our demo.
npx create-react-app name-of-your-app

Configure React Bootstrap Library:

Let's install the React Bootstrap library
npm install react-bootstrap bootstrap

Now add the bootstrap reference to the 'index.js'
src/index.js:
import 'bootstrap/dist/css/bootstrap.min.css'

Create A React Component 'Layout':

Let's create a react component like 'Layout' in the 'components/shared' folder(new folder).
src/components/shared/Layout.js:
import { Container } from "react-bootstrap";
import Navbar from "react-bootstrap/Navbar";

const Layout = ({ children }) => {
  return (
    <>
      <Navbar bg="primary" variant="dark">
        <Navbar.Brand href="#">Toy Store</Navbar.Brand>
      </Navbar>
      <Container>{children}</Container>
    </>
  );
};
export default Layout;
  • Here added our bootstrap Navbar component.
  • (Line: 10) Renders all our page components through the 'children' property.
Now render the 'Layout' element in the 'App' component.
src/App.js:
import "./App.css";
import Layout from "./components/shared/Layout";

function App() {
  return <Layout></Layout>;
}
export default App;

Install React Router Library:

Let's install the react-router library.
npm i react-router-dom

Now add the 'BrowserRouter' element in 'index.js'
src/index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

Setup JSON GraphQL Server:

Let's use JSON Server to set up a fake GraphQL endpoint in our local machine.

Now install the JSON GraphQL server globally.
npm i json-graphql-server

Create a db.js file within our angular application root folder. Define the API response type with sample data in  'db.js' as below.
db.js:
module.exports = {
  toys: [
    {
      id: 1,
      name: "Helicopter",
      price: 400,
      imageUrl:
        "",
    },
    {
      id: 2,
      name: "Army Tank",
      price: 700,
      imageUrl: "",
    },
  ],
};
In the 'package.json' file add the command to start the JSON GraphQL server.

Now start the GraphQL server, and run the below command in the terminal.
npm run json-server-gql

Then if we access the "http://localhost:4000" it opens up the GraphQL UI tool to interact with the graphQL server.

Install Apollo GraphQL Library:

Let's install the Apollo GraphQL Library.
npm install @apollo/client graphql

Initial Setup Of Apollo Graphql In ReactJS Application:

Let's configure the initial setup of our Apollo GraphQL client library.
src/index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter } from "react-router-dom";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  gql,
} from "@apollo/client";

const client = new ApolloClient({
  uri: "http://localhost:4000/",
  cache: new InMemoryCache(),
});

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <ApolloProvider client={client}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </ApolloProvider>
);
  • (Line: 14-17) Initialized the 'ApolloClient' that loads from the '@apollo/client' library. Here we configured our GraphQL endpoint URL and in-memory cache to store data.
  • (Line: 21-25) Rendered the 'ApolloProvider' component loads from the '@apolloclient'. Here we pass our 'Apolloclient' instance to the 'client' property.

Create A React Component 'AllToys':

Let's create a React Component like 'AllToys' in 'pages' folder(new folder).
src/pages/AllToys.js:
const AllToys = () => {
  return <></>;
};
export default AllToys;
Configure the route for our 'AllToys' component in the 'App' component.
src/App.js:
import { Route } from "react-router-dom";
import "./App.css";
import Layout from "./components/shared/Layout";
import AllToys from "./pages/AllToys";

function App() {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<AllToys />}></Route>
      </Routes>
    </Layout>
  );
}
export default App;

Implement Read Operation:

Let's implement the read operation by fetching data from the GraphQL endpoint.

Let's create GraphQL Query command to fetch all records from the GraphQL endpoint. So let's create a file like 'toysQuery.js' in 'graphql' folder(new folder).
src/graphql/toysQuery.js:
import { gql } from "@apollo/client";

export const GET_AllToys = gql`
  query {
    allToys {
      id
      name
      price
      imageUrl
    }
  }
`;
  • Here 'gql' loads from the '@apollo/client'
  • Here 'query' keyword represent GraphQL Query command
  • The 'allToys' is name of the method at the server.
  • The 'id', 'name', 'price', 'imageUrl' all are requested props from the server in the response.
Let's implement our logic in the 'AllToys' component as follow.
src/pages/AllToys.js:
import { useQuery } from "@apollo/client";
import { useEffect, useState } from "react";
import { Container } from "react-bootstrap";
import { GET_AllToys } from "../graphql/toysQuery";
import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";

const AllToys = () => {
  const [allToysData, setAllToysData] = useState([]);
  const { data } = useQuery(GET_AllToys, {
    fetchPolicy: "no-cache",
  });

  useEffect(() => {
    if (data?.allToys) {
      setAllToysData(data.allToys);
    }
  }, [data]);
  return (
    <>
      <Container className="mt-2">
        <Row xs={1} md={3} className="g-4">
          {allToysData.map((toy) => (
            <Col key={toy.id}>
              <Card>
                <Card.Img
                  variant="top"
                  src={toy.imageUrl}
                  style={{ height: 400, width: "100%" }}
                />
                <Card.Body>
                  <Card.Title>{toy.name}</Card.Title>
                  <Card.Text>Price - {toy.price}</Card.Text>
                </Card.Body>
              </Card>
            </Col>
          ))}
        </Row>
      </Container>
    </>
  );
};

export default AllToys;
  • (Line: 10) The 'allToysData' is a state variable to hold our API response.
  • (Line: 11-13) The 'useQuery' is to invoke the GraphQL query command. Here we passed our 'GET_AllToys' query command. The 'useQuery' by default uses cache, so to avoid cache we have to specify the value 'no-cache' to  'fetchPolicy'. Here we are reading 'data' property that contains the GraphQL API response.
  • (Line: 15-19) The 'useEffect' checks for the 'data' property value changes. Here we storing our API response into 'allToysData'. Here we use 'data.allToys' to read response data, the 'allToys' property is automatically added by server based on the server resolver method name and the same name we used while framing our Query command also.
  • (Line: 22-40) Here looping our API response data to bind.
(Step 1)

(Step: 2)

Create React Component 'AddToy':

Let's create a new ReactJS component like 'AddToy'.
src/pages/AddToy.js:
const AddToy = () => {
  return <></>;
};
export default AddToy;
Now configure the 'AddToy' component routing in 'App' component.
src/App.js:
import { Route, Routes } from "react-router-dom";
import "./App.css";
import Layout from "./components/shared/Layout";
import AddToy from "./pages/AddToy";
import AllToys from "./pages/AllToys";

function App() {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<AllToys />}></Route>
        <Route path="/add-toy" element={<AddToy />}></Route>
      </Routes>
    </Layout>
  );
}
export default App;

Implement Create Operation:

Let's implement create operation by adding the new item to our GraphQL server.

Let's create a GraphQL mutation command to create a new item at the GraphQL server. So let's create a new file like 'toyMutation.js' in 'graphql' folder.
src/graphql/toyMutation.js:
import { gql } from "@apollo/client";

export const CREATE_NewToy = gql`
  mutation ($name: String!, $price: Int!, $imageUrl: String!) {
    createToy(name: $name, price: $price, imageUrl: $imageUrl) {
      id
      name
      price
      imageUrl
    }
  }
`;
  • Here 'mutation' keyword its is the GraphQL mutation command
  • Here $name, $price, $imageUrl are GraphQL variables
  • (Line: 5)Here 'name', 'price', 'imageUrl'  are server variables
  • Here 'createToy' is our mutation method name at the server.
  • (Line: 6-9)Here 'id', 'name', 'price', 'imageUrl' are requesting properties from the server.
Let's add logic into our 'AddToy' component as follows.
src/pages/AddToy.js:
import { Col, Container, Row, Form, Button } from "react-bootstrap";
import { useRef } from "react";
import { useMutation } from "@apollo/client";
import { CREATE_NewToy } from "../graphql/toysMutation";
import { useNavigate } from "react-router-dom";

const AddToy = () => {
  const name = useRef("");
  const imageUrl = useRef("");
  const price = useRef("");

  const [addToy] = useMutation(CREATE_NewToy);

  const navigate = useNavigate();

  const addToyHandler = () => {
    addToy({
      variables: {
        name: name.current.value,
        imageUrl: imageUrl.current.value,
        price: Number(price.current.value),
      },
    }).then(() => {
      navigate("/");
    });
  };

  return (
    <>
      <Container className="mt-2">
        <Row>
          <Col className="col-md-8 offset-md-2">
            <legend>Add A Toy Form</legend>
            <Form.Group className="mb-3" controlId="formName">
              <Form.Label>Name</Form.Label>
              <Form.Control type="text" ref={name} />
            </Form.Group>
            <Form.Group className="mb-3" controlId="formPrice">
              <Form.Label>Price</Form.Label>
              <Form.Control type="text" ref={price} />
            </Form.Group>
            <Form.Group className="mb-3" controlId="formImageUrl">
              <Form.Label>Image Url</Form.Label>
              <Form.Control type="text" ref={imageUrl} />
            </Form.Group>
            <Button variant="primary" type="button" onClick={addToyHandler}>
              Add
            </Button>
          </Col>
        </Row>
      </Container>
    </>
  );
};
export default AddToy;
  • (Line: 8-10) Added the 'useRef' variables to read the form data.
  • (Line: 12) The 'useMutation()' loads from the '@apollo/client'. To this 'useMutation' we have to pass our mutation command like 'CREATE_NewToy'. Here we are reading function like 'addToy'.
  • (Line: 14) Declare 'useNavigate()' instance.
  • (Line: 16-28) Here we pass our form data to the GraphQL variable properties. The 'addToy' method invokes the GraphQL mutation request. On success, we navigate back to our home page.
In 'AllToys' component we have to create a button like 'Add' on clicking on it we must navigate to 'AddToy' component.
src/pages/AllToys.js:
import { useQuery } from "@apollo/client";
import { useEffect, useState } from "react";
import { Button, Container } from "react-bootstrap";
import { GET_AllToys } from "../graphql/toysQuery";
import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import { useNavigate } from "react-router-dom";

const AllToys = () => {
  const [allToysData, setAllToysData] = useState([]);
  const { data } = useQuery(GET_AllToys, {
    fetchPolicy: "no-cache",
  });
  const navigate = useNavigate();

  useEffect(() => {
    if (data?.allToys) {
      setAllToysData(data.allToys);
    }
  }, [data]);
  return (
    <>
      <Container className="mt-2">
        <Row>
          <Col className="col-md-4 offset-md-4">
            <Button
              variant="primary"
              type="button"
              onClick={() => {
                navigate("/add-toy");
              }}
            >
              Add
            </Button>
          </Col>
        </Row>
        <Row xs={1} md={3} className="g-4">
          <!-- code hidden for display purpose -->
        </Row>
      </Container>
    </>
  );
};

export default AllToys;
  • (Line: 27-35) The 'Add' button is configured.
(Step 1)

(Step 2)

(Step 3)

(Step 4)

Create React Component 'EditToy':

Let's create a new React component like 'EditToy' in the 'pages' folder.
src/pages/EditToy.js:
const EditToy = () => {
  return <></>;
};
export default EditToy;
Configure the route for the 'EditToy' component in the 'App' component.
src/App.js:
import { Route, Routes } from "react-router-dom";
import "./App.css";
import Layout from "./components/shared/Layout";
import AddToy from "./pages/AddToy";
import AllToys from "./pages/AllToys";
import EditToy from "./pages/EditToy";

function App() {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<AllToys />}></Route>
        <Route path="/add-toy" element={<AddToy />}></Route>
        <Route path="/edit-toy/:id" element={<EditToy />}></Route>
      </Routes>
    </Layout>
  );
}
export default App;
  • (Line: 14) The ':id' is the dynamic route placeholder, where we use our 'id' value in the route.

Implement Update Operation:

Let's implement the update operation by updating the items at our GraphQL endpoint.

Let's frame the GraphQL Query command to fetch a single item by 'id' value.
src/graphql/toyQuery.js:
export const GET_ToyById = gql`
  query ($id: ID!) {
    Toy(id: $id) {
      id
      name
      price
      imageUrl
    }
  }
`;
  • Here 'Toy' is a method at our GraphQL endpoint, so the 'Toy' method filters the data by the 'id' value. The '$id' variable name.
Let's frame the GraphQL Mutation command to update the item.
src/graphql/toyMutation.js:
export const UPDATE_Toy = gql`
  mutation ($id: ID!, $name: String, $price: Int, $imageUrl: String) {
    updateToy(id: $id, name: $name, price: $price, imageUrl: $imageUrl) {
      id
      name
      price
      imageUrl
    }
  }
`;
  • Here 'updateToy' is the method at our GraphQL endpoint for updating the item. The '$id', '$name', '$price', '$imageUrl' are GraphQL variables.
Let's add our logic in the 'EditToy' component
src/pages/EditToy.js:
import { Col, Container, Row, Form, Button } from "react-bootstrap";
import { useEffect, useRef } from "react";
import { useMutation, useQuery } from "@apollo/client";
import { GET_ToyById } from "../graphql/toysQuery";
import { useNavigate, useParams } from "react-router-dom";
import { UPDATE_Toy } from "../graphql/toysMutation";
const EditToy = () => {
  const name = useRef("");
  const imageUrl = useRef("");
  const price = useRef("");
  const { id } = useParams();
  const navigate = useNavigate();
  const { data } = useQuery(GET_ToyById, {
    variables: { id: Number(id) },
  });

  const [updateToy] = useMutation(UPDATE_Toy);

  useEffect(() => {
    if (data?.Toy) {
      name.current.value = data.Toy.name;
      price.current.value = data.Toy.price;
      imageUrl.current.value = data.Toy.imageUrl;
    }
  }, [data]);

  const updateToyHandler = () => {
    updateToy({
      variables: {
        id: Number(id),
        name: name.current.value,
        imageUrl: imageUrl.current.value,
        price: Number(price.current.value),
      },
    }).then(() => {
      navigate("/");
    });
  };

  return (
    <>
      <Container className="mt-2">
        <Row>
          <Col className="col-md-8 offset-md-2">
            <legend>Update A Toy Form</legend>
            <Form.Group className="mb-3" controlId="formName">
              <Form.Label>Name</Form.Label>
              <Form.Control type="text" ref={name} />
            </Form.Group>
            <Form.Group className="mb-3" controlId="formPrice">
              <Form.Label>Price</Form.Label>
              <Form.Control type="text" ref={price} />
            </Form.Group>
            <Form.Group className="mb-3" controlId="formImageUrl">
              <Form.Label>Image Url</Form.Label>
              <Form.Control type="text" ref={imageUrl} />
            </Form.Group>
            <Button variant="primary" type="button" onClick={updateToyHandler}>
              Update
            </Button>
          </Col>
        </Row>
      </Container>
    </>
  );
};
export default EditToy;
  • (Line: 8-10) The 'useRef' variable to read the form data.
  • (Line: 11) Using the 'useParam' value read the 'id' value from the URL.
  • (Line: 12) Initialized the 'useNavigate'.
  • (Line: 13-15) The 'useQuery' helps to read the data from the GraphQL endpoint. Here we are fetching our item to edit.
  • (Line: 17) The 'useMutation' helps to change the data at the server. Here we writing a mutation command for updating the record. The 'updateToy' method will used to invoke the GraphQL API call.
  • (Line: 19-25) Inside of the 'useEffect' method we are populating our Edit form. The 'data.Toy' contains our item, the 'Toy' property name must match with the name we defined in the Query command(GET_ToyById).
  • (Line: 27-38) Using the 'updateToy' method we assign our form data to the GraphQL variable and then invoke the GraphQL endpoint for updating the item.
The 'Edit' button of each item in 'AllToys' component.
src/pages/AllToys.js:
<Card.Body>
  <Card.Title>{toy.name}</Card.Title>
  <Card.Text>Price - {toy.price}</Card.Text>
  <Button
	variant="primary"
	type="button"
	onClick={() => navigate(`/edit-toy/${toy.id}`)}
  >
	Edit
  </Button>
</Card.Body>
(Step 1)

(Step 2)

(Step 3)

Implement Delete Operation:

Let's implement the Delete operation to delete an item at the GraphQL server.

Let's create a GraphQL mutation command to remove an item from the server.
src/graphql/toyMutation.js:
export const DELETE_ToyById = gql`
  mutation ($id: ID!) {
    removeToy(id: $id) {
      id
    }
  }
`;
Let's created a shared delete modal confirmation component like 'DeleteConfirmation' in the 'components/shared' folder.
src/components/shared/DeleteConfirmation.js:
import Button from "react-bootstrap/Button";
import Modal from "react-bootstrap/Modal";
const DeleteConfirmation = (props) => {
  return (
    <>
      <Modal show={props.showModal} onHide={() => {props.closeConfirmDeleteModalHandler()}}>
        <Modal.Header closeButton>
          <Modal.Title>{props.title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>{props.body}</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => {props.closeConfirmDeleteModalHandler()}}>
            Close
          </Button>
          <Button variant="danger" onClick={() => {props.confirmDeleteHandler()}}>
            Confirm Delete
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};
export default DeleteConfirmation;
  • Here 'DeleteConfirmation' component contains react-bootstrap modal code.
  • (Line: 6) The 'show' is the boolean property of the 'Modal' component. The parent component passes its value through 'props.showModal'(here showModal is our custom property name which must be passed by the parent component and its value should be a boolean). So if 'show' property receives 'true' then opens the modal.
  • (Line: 6) The 'onHide' get triggered by the 'X'(close button) on the right-top corner of the modal. Here 'onHide' register with an arrow function that internally calls a method of the parent component like 'props.closeConfirmDeleteModalHandler'.
  • (Line: 8) Dynamic 'prop.title' property for the modal title.
  • (Line: 10) Dynamic 'prop.body' property for the modal body.
  • (Line: 12-14)Close button click event register with arrow function which internally call the method of parent component like 'props.closeConfirmDeleteModalHandler'.
  • (Line: 15-17) Confirm delete button, click event register with arrow function which internally calls a method of parents component like 'props.confirmDeleteHandler'.
Let's invoke the 'DeleteConfirmation' component modal from the 'AllToys' component.
src/pages/AllToys.js:
import { useMutation, useQuery } from "@apollo/client";
import { useEffect, useState } from "react";
import { Button, Container } from "react-bootstrap";
import { GET_AllToys } from "../graphql/toysQuery";
import Card from "react-bootstrap/Card";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import { useNavigate } from "react-router-dom";
import { DELETE_ToyById } from "../graphql/toysMutation";
import DeleteConfirmation from "../components/shared/DeleteConfirmation";

const AllToys = () => {
  const [allToysData, setAllToysData] = useState([]);
  const { data } = useQuery(GET_AllToys, {
    fetchPolicy: "no-cache",
  });
  const navigate = useNavigate();

  const [itemIDToDelete, setItemIDToDelete] = useState(0);
  const [showModal, setShowModal] = useState(false);

  const [deleteToy] = useMutation(DELETE_ToyById);

  useEffect(() => {
    if (data?.allToys) {
      setAllToysData(data.allToys);
    }
  }, [data]);

  const openConfirmDeleteModalHandler = (id) => {
    setItemIDToDelete(id);
    setShowModal(true);
  };

  const closeConfirmDeleteModalHandler = () => {
    setItemIDToDelete(0);
    setShowModal(false);
  };

  const confirmDeleteHandler = () => {
    deleteToy({
      variables: {
        id: itemIDToDelete,
      },
    }).then(() => {
      setAllToysData((existingData) => {
        return existingData.filter((_) => _.id != itemIDToDelete);
      });
      setItemIDToDelete(0);
      setShowModal(false);
    });
  };

  return (
    <>
      <DeleteConfirmation
        showModal={showModal}
        title="Delete Confirmation"
        body="Are you sure you want to delete item?"
        closeConfirmDeleteModalHandler={closeConfirmDeleteModalHandler}
        confirmDeleteHandler={confirmDeleteHandler}
      ></DeleteConfirmation>
      <Container className="mt-2">
        <Row>
          <Col className="col-md-4 offset-md-4">
            <Button
              variant="primary"
              type="button"
              onClick={() => {
                navigate("/add-toy");
              }}
            >
              Add
            </Button>
          </Col>
        </Row>
        <Row xs={1} md={3} className="g-4">
          {allToysData.map((toy) => (
            <Col key={toy.id}>
              <Card>
                <Card.Img
                  variant="top"
                  src={toy.imageUrl}
                  style={{ height: 400, width: "100%" }}
                />
                <Card.Body>
                  <Card.Title>{toy.name}</Card.Title>
                  <Card.Text>Price - {toy.price}</Card.Text>
                  <Button
                    variant="primary"
                    type="button"
                    onClick={() => navigate(`/edit-toy/${toy.id}`)}
                  >
                    Edit
                  </Button>
                  |
                  <Button
                    variant="danger"
                    type="button"
                    onClick={() => openConfirmDeleteModalHandler(toy.id)}
                  >
                    Delete
                  </Button>
                </Card.Body>
              </Card>
            </Col>
          ))}
        </Row>
      </Container>
    </>
  );
};
export default AllToys;
  • (Line: 19) The 'itemIDToDelete' state variable to store the 'id' value of the item we have to delete.
  • (Line: 20) The 'showModal' state variable to store boolean for hide & show modal
  • (Line: 22) The 'useMutation' method regierter with our delete mutation command and we are reading the function reference as 'deleteToy'.
  • (Line: 30-33) The 'openConfirmDeleteModalHandler' opens the modal. Here we save our item to delete 'id' value into the 'itemIDToDelete' state variable.
  • (Line: 35-30) The 'closeConfirmDeleteModalHandler' closes the modal by setting 'false' value to 'showModal' state variable. Here we reset the 'itemIDToDelete' value to '0'.
  • (Line: 40-52) The 'confirmDeleteHanlder' invokes the GraphQL endpoint using  'deleteToy' method.
  • Here after API success, remove the item from the 'setAllToysData' state variable
  • (Line: 56-62) Add the 'DeleteConfirmation' component element render with its input props
  • (Line: 97-103) Added the 'Delete' button.

Implement Create Operation Using Cache:

So after creating a new item at the GraphQL server we can save the item into our In-memory cache.

Remove the 'fetchpolicy:no-cache' property from the 'useQuery()' method in the 'AllToys' component

Now update our 'addToyHandler' method in the 'AddToy' component.
src/pages/AddToy.js:
const addToyHandler = () => {
    addToy({
      variables: {
        name: name.current.value,
        imageUrl: imageUrl.current.value,
        price: Number(price.current.value),
      },
      update(cache, { data: { createToy } }) {
        cache.modify({
          fields: {
            allToys(existingToys = []) {
              const newToyRef = cache.writeFragment({
                data: createToy,
                fragment: gql`
                  fragment newToy on Todo {
                    id
                    name
                    price
                    imageUrl
                  }
                `,
              });
              return [...existingToys, newToyRef];
            },
          },
        });
      },
    }).then(() => {
      navigate("/");
    });
  };
  • (Line: 8) The 'update' method executes on GraphQL API success. The first parameter is 'cache' which is an instance of the in-memory cache. The second parameter is 'data:{createToy}' is the response from the GraphQL endpoint.
  • (Line: 9) Now go to 'cache.modify' then go to  'fields', then create a method like 'allToys' method. The name 'allToys' is the name of the response object of our 'GET_AllToys' query command in the 'AllToys' component. To this method we are accessing all the data from the cache as 'existingToys' array variable.
  • (Line: 12) The 'cache.writeFragment' helps to push our newly created record as fragment of data into the in-memory cache.
  • (Line: 12-13) Crating our newly created item as graphQL fragment
  • (Line: 23) Updating our newly created item into the in-memory cache.

Implement Update Operation Using Cache:

In 'EditToy' component let's change our update mutation call to use the cache.
src/pages/EditToy.js:
 const updateToyHandler = () => {
    updateToy({
      variables: {
        id: Number(id),
        name: name.current.value,
        imageUrl: imageUrl.current.value,
        price: Number(price.current.value),
      },
      update(cache, { data: { updateToy } }) {
        cache.modify({
          fields: {
            allToys(existingData = [], { readField }) {
              existingData = existingData.filter(
                (item) => updateToy.id !== readField("id", item)
              );
              const updatToyRef = cache.writeFragment({
                data: updateToy,
                fragment: gql`
                  fragment newToy on Toy {
                    id
                    name
                    price
                    imageUrl
                  }
                `,
              });
              return [...existingData, updatToyRef];
            },
          },
        });
      },
    }).then(() => {
      navigate("/");
    });
  }
  • (Line: 9) The 'update' method executes on GraphQL API success. The first parameter is 'cache' which is an instance of the in-memory cache. The second parameter is 'data:{updateToy}' is the response from the GraphQL endpoint.
  • (Line: 10-11) Now go to 'cache.modify' then go to  'fields', then create a method like 'allToys' method. The name 'allToys' is the name of the response object of our 'GET_AllToys' query command in the 'AllToys' component. To this method we are accessing all the data from the cache as 'existingToys' array variable. The 'readField' helps to read the particular object property in cache
  • (Line: 13-15) The item data before updating is remove from the cache-memory
  • (Line: 16-26) Creating our updated item as a new fragment.
  • (Line: 27) Pushing our updated item into the cache.

Implement Delete Operation Using Cache:

In 'AllToys' component let's change our delete mutation call to use the cache.
src/pages/AllToys.js:
const confirmDeleteHandler = () => {
    deleteToy({
      variables: {
        id: itemIDToDelete,
      },
      update(cache, { data: { removeToy } }) {
        cache.modify({
          fields: {
            allToys(existingData = [], { readField }) {
              existingData = existingData.filter(
                (item) => removeToy.id !== readField("id", item)
              );
              return existingData;
            },
          },
        });
      },
    }).then(() => {
      // setAllToysData((existingData) => {
      //   return existingData.filter((_) => _.id != itemIDToDelete);
      // });
      setItemIDToDelete(0);
      setShowModal(false);
    });
  };
  • (Line: 6) The 'update' method executes on GraphQL API success. The first parameter is 'cache' which is an instance of the in-memory cache. The second parameter is 'data:{removeToy}' is the response from the GraphQL endpoint.
  • (Line: 7-9) Now go to 'cache.modify' then go to  'fields', then create a method like 'allToys' method. The name 'allToys' is the name of the response object of our 'GET_AllToys' query command in the 'AllToys' component. To this method we are accessing all the data from the cache as 'existingToys' array variable. The 'readField' helps to read the particular object property in cache.
  • (10-12)The item data before updating is remove from the cache-memory.
  • (19-21) Now we can remove the code like manually excluding our deleted item from the 'allToysData' variable.

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on the ReactJS(v18) GraphQL CRUD example. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

Comments

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n