React结合Graphql使用

服务端

这一节只介绍react中的用法
GraphQL 从入门到实践
服务端github代码

安装

在你的react项目中需要先安装几个包

npm i react-apollo apollo-boost graphql graphql-tag

ApolloClient配置

import { ApolloProvider } from "react-apollo";
import ApolloClient from "apollo-boost";
const client = new ApolloClient({
  uri: "http://localhost:4000/"
});

ReactDOM.render(
  
    
  ,
  document.getElementById("root")
);

Query

  1. 无参数
import { Query, graphql } from "react-apollo";
import gql from "graphql-tag";
const users = gql`
  {
    users {
      name
      age
      gender
      email
    }
  }
`;
function Users() {
  return (
    
      {({ loading, error, data }) => {
        return (
          <>
            {!loading &&
              data.users.map(item => (
                
name: {item.name} age: {item.age} gender: {item.gender} email: {item.email}
))} ); }}
) }
  1. 参数
const USER = gql`
  query User($id: String!) {
    user(id: $id) {
      name
    }
  }
`;

function User() {
  const [id, setId] = useState("2");
  return (
    <>
      

User

setId(e.target.value)} /> {({ loading, error, data }) => { return ( !loading && (
name: {data.user.name} age: {data.user.age} gender: {data.user.gender} email: {data.user.email}
) ); }}
); }

Mutations

const CREATE_USER = gql`
  mutation CreateUser(
    $id: ID!
    $name: String!
    $email: String!
    $age: Int
    $gender: Gender
  ) {
    createUser(
      id: $id
      name: $name
      email: $email
      age: $age
      gender: $gender
    ) {
      id
      name
      email
      age
    }
  }
`;

function User() {
  const [id, setId] = useState("1");
  const [name, setName] = useState("张三");
  const [email, setEmail] = useState("[email protected]");
  const [age, setAge] = useState();
  const [gender, setGender] = useState();
  return (
    <>
      

Create User

{(createUser, { data }) => { console.log(createUser); return (
{ e.preventDefault(); createUser({variables : {id, name, email, age, gender}}) }} > *id: setId(e.target.value)} /> *name: setName(e.target.value)} /> *email: setEmail(e.target.value)} /> age: setAge(e.target.value)} /> gender: setGender(e.target.value)} placeholder="MAN WOMAN" />
); }}
); }

Subscription

你可能感兴趣的:(React结合Graphql使用)