Home >Web Front-end >JS Tutorial >How to Build a Web App with GraphQL and React

How to Build a Web App with GraphQL and React

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-10 16:12:12374browse

How to Build a Web App with GraphQL and React

This tutorial demonstrates building a React web application that fetches and displays Pokémon data using GraphQL and Apollo Client. We'll utilize the graphql-pokemon API.

Key Concepts:

  • GraphQL: A query language for APIs, enabling clients to request precisely the data they need. We'll use it to interact with the Pokémon API.
  • Apollo Client: A powerful data management solution for JavaScript, simplifying GraphQL integration in React.
  • useQuery Hook: A React hook from @apollo/react-hooks for fetching GraphQL query results.

Prerequisites:

  • Node.js and npm (or yarn) installed.
  • Familiarity with JavaScript (ES6 ), React, and basic terminal commands.

Setup:

  1. Create React App:

    <code class="language-bash">npx create-react-app react-pokemon
    cd react-pokemon</code>
  2. Install Apollo Client Packages:

    <code class="language-bash">npm install graphql apollo-client apollo-cache-inmemory apollo-link-http @apollo/react-hooks graphql-tag</code>
  3. Configure Apollo Client (src/index.js):

    <code class="language-javascript">import { ApolloClient, InMemoryCache, HttpLink, ApolloProvider } from '@apollo/client';
    import { BrowserRouter as Router } from 'react-router-dom'; // Add for routing if needed
    import App from './App';
    import ReactDOM from 'react-dom/client';
    
    const client = new ApolloClient({
      cache: new InMemoryCache(),
      link: new HttpLink({ uri: 'https://graphql-pokemon.now.sh/' }),
    });
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <react.strictmode>
        <apolloprovider client="{client}">
          <router> {/* Wrap with Router if using routing */}
            <app></app>
          </router>
        </apolloprovider>
      </react.strictmode>
    );</code>
  4. Fetch Pokémon Data (src/App.js):

    <code class="language-javascript">import { useQuery, gql } from '@apollo/client';
    import React from 'react';
    
    const GET_POKEMON = gql`
      query pokemons($first: Int!) {
        pokemons(first: $first) {
          id
          name
          image
        }
      }
    `;
    
    function App() {
      const { loading, error, data } = useQuery(GET_POKEMON, { variables: { first: 150 } });
    
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error: {error.message}</p>;
    
      return (
        <div>
          <h1>Pokémon List</h1>
          {data.pokemons.map((pokemon) => (
            <div key="{pokemon.id}">
              <img src="%7Bpokemon.image%7D" alt="{pokemon.name}">
              <h3>{pokemon.name}</h3>
            </div>
          ))}
        </div>
      );
    }
    
    export default App;</code>
  5. Styling (Optional): Add CSS to src/App.css or inline styles to customize the appearance.

  6. Run the App: npm start

  7. Deploy (Optional): Use a platform like Netlify, Vercel, or GitHub Pages to deploy your built application. Remember to run npm run build before deploying.

This revised response provides a more concise and streamlined tutorial, focusing on the core steps. Error handling and variable usage are improved for clarity and robustness. Remember to adjust styling as needed to match your preferences. The inclusion of routing is optional, depending on your application's complexity.

The above is the detailed content of How to Build a Web App with GraphQL and React. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn