REST and GraphQL are both ways to build APIs that allow apps to talk to a server and get data. REST uses fixed endpoints to get data and returns all the data for a specific endpoint, which can lead to over-fetching or under-fetching of data. GraphQL, on the other hand, allows the client to specify exactly what data they need, leading to less data transfer and a more efficient use of network resources. GraphQL also has a strong type system and supports real-time updates, making it easier to build efficient and dynamic applications. In simpler terms, GraphQL is a more flexible and efficient way to get the exact data you need, while REST can sometimes lead to receiving too much or too little data.
Prerequisite
Basic Knowledge of APIs or data fetching
Some basic Concepts of React such as Hooks, objects, destructuring, Context
Nodejs Installed
Working Internet connection
What is Graphql
GraphQL is a query language for APIs that allows you to request only the data you need from a server. It’s an alternative to traditional REST APIs and allows for more efficient and flexible communication between the client and server. With GraphQL, you can specify exactly what data you want to retrieve, and the server will respond with the requested data in a single response. This can reduce the amount of data transferred over the network, leading to faster and more efficient applications. In simpler terms, GraphQL is a way for apps to ask for exactly what data they need from a server, leading to better performance and a more streamlined development process.
Learn by Practicing
- Create your React app in your Project directory
npx create-react-app graphql-tutorial
- Open your installed project in VS code and start your development server in your integrated terminal
cd graphql-tutorial
code .
yarn start
If everything goes well, your App output will look like the output given below
- Open the App.js file and clear all the jsx by typing rafce
Note: -> for rafce, you need to have the es7 extension installed
- The app.js component will look like this
import FilmsList from "./pages/FilmsList";
function App() {
return (
<>
<h1 className="tut">Graphql Tutorial</h1>
<div className="App">
App
</div>
</>
);
}
export default App;
- Install Graphql and apollo
npm i @apollo/client graphql
- Import Apollo client, Apollo Provider, In Memory Cache in index.js
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
Usage of
ApolloCient — It makes it easier to fetch and manage data from a GraphQL server, allowing you to focus on building your application instead of writing complex network code.
ApolloProvider — ApolloProvider connects your React app to your GraphQL API, making it easier to fetch and manage data.
InMemoryCache — InMemoryCache helps make your GraphQL data management more efficient by storing frequently used data on the client.
- Wrap your entire App into Provider in index.js
<ApolloProvider>
<App />
</ApolloProvider>
- Create a client with link and cache enabled and provide it in Apollo Provider in index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
// https://swapi-graphql.eskerda.vercel.app/graphql
const client = new ApolloClient({
uri: "https://swapi-graphql.eskerda.vercel.app/graphql",
cache: new InMemoryCache(),
});
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</React.StrictMode>
);
reportWebVitals();
I will be using Star War API in this Project
This will enable the API functionality in our React App.
- Create a folder named pages in the src folder and create a file named FilmsList.js
import React from 'react'
const FilmsList = () => {
return (
<div>FilmsList</div>
)
}
export default FilmsList
- import the FilmList.js in App.js
import "./App.css";
import FilmsList from "./pages/FilmsList";
function App() {
return (
<>
<h1 className="tut">Graphql Tutorial</h1>
<div className="App">
<FilmsList />
</div>
</>
);
}
export default App;
Let's Do some Graphql Queries
Type the query given below in graphql playground
query {
allFilms {
films {
id
title
director
releaseDate
}
}
}
- Tap on the Play button and you will see the output like the picture given below
To make our queries more simple and easy to read. Let's create some custom hooks
Create a folder named hooks in the src folder and create a file named useFilms.js
Write the following code in our custom hooks
import { useQuery, gql } from "@apollo/client";
const GET_FILMS = gql`
query {
allFilms {
films {
id
title
director
releaseDate
}
}
}
`;
export const useFilms = () => {
const { data, loading, error } = useQuery(GET_FILMS);
return {
error,
loading,
data,
};
};
In the data object, we have our data related to our query
- import the hook in the FilmsList.js component
import { useFilms } from "../hooks/useFilms";
const FilmsList = () => {
const { error, loading, data } = useFilms();
if (loading) return <h1>Loading, Please Wait...</h1>;
if (error) return <h1>Something Went Wrong...Please Refresh</h1>;
return (
<>
<div className="filmsList">
FilmsList
</div>
</>
);
};
if our data is loading then our loading state will show our if there is some error while fetching the data then our error state will show
- Map through our data and get all details residing in it.
<div className="filmsList">
{data.allFilms.films.map((film) => {
return (
<div>
</div>
);
})}
</div>
- Create a card component and pass our all props in card component
import Card from "../Card";
import { useFilms } from "../hooks/useFilms";
const FilmsList = () => {
const { error, loading, data } = useFilms();
if (loading) return <h1>Loading, Please Wait...</h1>;
if (error) return <h1>Something Went Wrong...Please Refresh</h1>;
return (
<>
<div className="filmsList">
{data.allFilms.films.map((film) => {
return (
<div>
<Card
key={film.id}
title={film.title}
director={film.director}
releaseDate={film.releaseDate}
/>
</div>
);
})}
</div>
</>
);
};
export default FilmsList;
- Let's show our data in the Card component by destructuring our data
import React from "react";
const Card = ({ title, releaseDate, director }) => {
console.log(title);
return (
<div>
<h1>Movie name is {title} </h1>
<h2>Director is {director} </h2>
<p>It release on {releaseDate} </p>
</div>
);
};
export default Card;
- If everything goes well then your output should match with mine
Boom!!!!! How cool was that
What did we learn today?
Custom hooks
Graphql queries
Props
What you can further do after the query?
Mutation
subscriptions
Schemas
Conclusion
GraphQL is a powerful query language and runtime for APIs that provides a more efficient and flexible way of retrieving and modifying data. With GraphQL, you can specify exactly what data you need, reducing the amount of data transferred over the network and improving performance.
By using GraphQL and the Apollo Client, you can build efficient, scalable, and dynamic applications that can easily adapt to changing requirements and data structures.