16
loading...
This website collects cookies to deliver better user experience
For more information on Apollo Client, feel free to read its documentation.
npm install @apollo/client graphql
index.js
, let us initialize an ApolloClient
instance by importing the following:import {
ApolloClient,
InMemoryCache,
ApolloProvider
} from "@apollo/client";
const client = new ApolloClient({
uri: 'https://beta.pokeapi.co/graphql/v1beta',
cache: new InMemoryCache()
});
uri
refers to the endpoint of the GraphQL API. As shown in the screenshot below, our PokeAPI is located at: https://beta.pokeapi.co/graphql/v1beta
ApolloProvider
component around our App
component, passing client
as a prop.ReactDOM.render(
<ApolloProvider client={client}>
<React.StrictMode>
<App />
</React.StrictMode>
</ApolloProvider>,
document.getElementById('root')
);
src
folder, let's create a gql
folder. This is where we will write all our queries or mutation. It keeps the code organized.gql
folder, create a file called Query.js
, where we will write our query to fetch data from the PokeAPI.gql/Query.js
, we will first import gql
, then export and write our GraphQL query inside it like so:import { gql } from "@apollo/client";
export const GET_GEN_3 = gql`
query getGen3 {
pokemon_v2_pokemonspecies(
order_by: { id: asc }
where: { pokemon_v2_generation: { name: { _eq: "generation-iii" } } }
) {
name
id
}
}
`;
name
and id
that were from Generation 3 aka Hoenn region (i.e. created in 2003).App.js
. Import the useQuery
Hook and the query:import { useQuery } from '@apollo/client';
import { GET_GEN_3 } from "./gql/Query";
function App() {
const { loading, error, data } = useQuery(GET_GEN_3);
console.log(data);
//...
}
npm start
and we should see our Pokémon data has been successfully fetched in the following format:App.js
, we can simply use conditionals and map the data like this:return (
<div className="App">
<header className="App-header">
{loading ? (
<img src={logo} className="App-logo" alt="logo" />
) : error ? (
<p>Error: {error}</p>
) : (
<div>
{data.pokemon_v2_pokemonspecies.map((pokemon) => {
return (
<p>
{pokemon.id} {pokemon.name}
</p>
);
})}
</div>
)}
</header>
</div>
);
pokemon_v2_pokemonspecies
array and print each Pokemon's name
and id
.