[GraphQL] Apollo React Query Component

何昆
2023-12-01

In this lesson I refactor a React component that utilizes the graphql higher-order component to the new Query render prop component baked into react-apollo.

Additional Resources: What's next for React Apollo

 

import React from "react";
import { render } from "react-dom";
import ApolloClient, { gql } from "apollo-boost";
import { ApolloProvider, Query } from "react-apollo";

const client = new ApolloClient({ uri: "https://graphql-pokemon.now.sh" });

const GET_POKEMON = gql`
  query($name: String!) {
    pokemon(name: $name) {
      name
      image
    }
  }
`;

const Pokemon = ({ name, image }) => {
  return (
    <div>
      <div>{name}</div>
      <img src={image} />
    </div>
  );
};

const PokemonQuery = () => (
  <Query query={GET_POKEMON} variables={{ name: "pikachu" }}>
    {({ loading, error, data }) => {
      if (loading) return <div>Loading...</div>;
      if (error) return <div>Error</div>;
      return <Pokemon name={data.pokemon.name} image={data.pokemon.image} />;
    }}
  </Query>
);

const ApolloApp = () => (
  <ApolloProvider client={client}>
    <PokemonQuery />
  </ApolloProvider>
);

render(<ApolloApp />, document.getElementById("root"));

 

 

 类似资料: