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
Release: 2025-02-10 16:12:12
Original
393 people have browsed it

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:

    npx create-react-app react-pokemon
    cd react-pokemon
    Copy after login
  2. Install Apollo Client Packages:

    npm install graphql apollo-client apollo-cache-inmemory apollo-link-http @apollo/react-hooks graphql-tag
    Copy after login
  3. Configure Apollo Client (src/index.js):

    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 />
          </Router>
        </ApolloProvider>
      </React.StrictMode>
    );
    Copy after login
  4. Fetch Pokémon Data (src/App.js):

    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={pokemon.image} alt={pokemon.name} />
              <h3>{pokemon.name}</h3>
            </div>
          ))}
        </div>
      );
    }
    
    export default App;
    Copy after login
  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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template