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

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'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update 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 the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the 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 the authentication with HTTP-only JWT cookie then we no need to implement the 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 authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.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

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

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

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

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS 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 CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

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