Home >Web Front-end >JS Tutorial >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:
useQuery
Hook: A React hook from @apollo/react-hooks
for fetching GraphQL query results.Prerequisites:
Setup:
Create React App:
<code class="language-bash">npx create-react-app react-pokemon cd react-pokemon</code>
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>
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>
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>
Styling (Optional): Add CSS to src/App.css
or inline styles to customize the appearance.
Run the App: npm start
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!