1. 程式人生 > >React-Apollo-Prisma-Graphql

React-Apollo-Prisma-Graphql

nbsp 事先 local amp -- pan www mes targe

  create-react-app: https://facebook.github.io/create-react-app/docs/getting-started  

  Apollo:https://www.graphql.college/building-a-github-client-with-react-apollo/

  Prisma:https://www.prisma.io/docs/

  首先,在創建客戶端之前,跟著Prisma教程起一個server,我這裏的server地址:localhost:4000。然後,跟著create-react-app創建一個react項目,啟動。

  接著,在react項目中安裝依賴:

npm install apollo-boost react-apollo graphql --save

  創建一個客戶端,並且指向Graphql服務器:

1 import ApolloClient from apollo-boost;
2 
3 const client = new ApolloClient({
4   uri: "http://localhost:4000"
5 });

  創建一個Provider,直接用react-apollo裏的ApplloProvider組件,用ApolloProvider作為一個容器去包裹其他需要訪問Graphql服務器數據的react組件。

import { ApolloProvider } from "react-apollo";
 1 class App extends Component {
 2   render() {
 3     return (
 4       <ApolloProvider client={client}>
 5       <div>
 6         <h2>My first Apollo app ??</h2>
 8       </div>
 9     </ApolloProvider>
10     );
11
} 12 }

  現在我們已經創建好了ApolloClient實例並且使用ApolloRrovider將client傳進react組件,可以開始從Graphql服務器中取數據到react組件中了。引入gql和Query,查詢我們事先在Graphql服務器上事先建好的數據,以下數據查詢已有的panel並顯示panel的id和title。

import gql from "graphql-tag";
import { Query } from "react-apollo";
const ExchangeRates = () => (
  <Query
    query={gql`
      query {
        panels{
          id
          title
        }
      }
    `}
    errorPolicy="all"
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;

      return (
        <div>
          <h1>{data && data.panels[0].title}</h1>
          {error && (
            <pre>
              <code>
                {error &&
                  error.graphQLErrors[0] &&
                  error.graphQLErrors[0].message}
              </code>
            </pre>
          )}
          {data && data.panels && <h3>{data.panels[0].title}</h3>}
        </div>
      );
    }}
  </Query>
);

  將ExchangeRates添加到react組件中,完畢。

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
      <div>
        <h2>My first Apollo app ??</h2>
        <ExchangeRates />
      </div>
    </ApolloProvider>
    );
  }
}

React-Apollo-Prisma-Graphql