DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to call GraphQL API in React.js

To call a GraphQL API in a React.js application, you can use a variety of methods. One popular approach is to use a library like Apollo Client, Relay, or even plain HTTP requests. Below, I'll provide a simple example using Apollo Client, a widely used GraphQL client library for React:

  1. Install Apollo Client: Make sure you have Node.js and npm installed. In your React project directory, run:
   npm install @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode
  1. Setup Apollo Client: Create an Apollo Client instance and wrap your React application with the ApolloProvider. This usually happens in your main index.js or App.js file.
   // index.js or App.js
   import React from 'react';
   import { ApolloProvider } from '@apollo/client';
   import { ApolloClient, InMemoryCache } from '@apollo/client';

   const client = new ApolloClient({
     uri: 'https://example.com/graphql', // Replace with your GraphQL API endpoint
     cache: new InMemoryCache(),
   });

   const App = () => (
     <ApolloProvider client={client}>
       {/* Your React components go here */}
     </ApolloProvider>
   );

   export default App;
Enter fullscreen mode Exit fullscreen mode
  1. Perform a GraphQL Query: Now, you can use the useQuery hook from @apollo/client to perform GraphQL queries in your components.
   // ExampleComponent.js
   import React from 'react';
   import { useQuery, gql } from '@apollo/client';

   const GET_DATA = gql`
     query {
       // Your GraphQL query goes here
       // For example, if you have a "users" query:
       users {
         id
         name
       }
     }
   `;

   const ExampleComponent = () => {
     const { loading, error, data } = useQuery(GET_DATA);

     if (loading) return <p>Loading...</p>;
     if (error) return <p>Error: {error.message}</p>;

     return (
       <div>
         {data.users.map(user => (
           <div key={user.id}>{user.name}</div>
         ))}
       </div>
     );
   };

   export default ExampleComponent;
Enter fullscreen mode Exit fullscreen mode
  1. Mutations and Additional Features: For mutations or more complex use cases, you can use the useMutation hook or other features provided by Apollo Client.

Remember to replace the GraphQL endpoint (uri in ApolloClient) with the actual endpoint of your GraphQL API. Additionally, adjust the GraphQL queries and mutations according to your API schema.

Top comments (0)