In this article, we will understand the Apollo GraphQL library to consume the GraphQL Endpoint in the ReactJS application with a sample CRUD example.
Now start the GraphQL server, and run the below command in the terminal.
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.
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.
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.
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: 2)
Create React Component 'AddToy':
Let's create a new ReactJS component like 'AddToy'.
src/pages/AddToy.js:
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.
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.
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 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.
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.
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.
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'.
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.
Comments
Post a Comment