The service side
This section only introduces the use of GraphQL in React from getting started to practicing server-side Github code
The installation
Install several packages in your React project
npm i react-apollo apollo-boost graphql graphql-tag
Copy the code
ApolloClient configuration
import { ApolloProvider } from "react-apollo";
import ApolloClient from "apollo-boost";
const client = new ApolloClient({
uri: "http://localhost:4000/"
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root"));Copy the code
Query
- There is no parameter
import { Query, graphql } from "react-apollo";
import gql from "graphql-tag";
const users = gql`
{
users {
name
age
gender
email
}
}
`;
function Users() {
return (
<Query query={users}>
{({ loading, error, data }) => {
return(< > {! loading && data.users.map(item => ( <div> name: {item.name} age: {item.age} gender: {item.gender} email: {item.email} <br /> </div> ))} </> ); }} </Query> ) }Copy the code
- parameter
const USER = gql`
query User($id: String!) {
user(id: $id) {
name
}
}
`;
function User() {
const [id, setId] = useState("2");
return (
<>
<h1>User</h1>
<input placeholder="input id" onChange={e => setId(e.target.value)} />
<Query query={USER} variables={{ id }}>
{({ loading, error, data }) => {
return (
!loading && (
<div>
name: {data.user.name}
age: {data.user.age}
gender: {data.user.gender}
email: {data.user.email}
<br />
</div>
)
);
}}
</Query>
</>
);
}
Copy the code
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("Zhang");
const [email, setEmail] = useState("[email protected]");
const [age, setAge] = useState();
const [gender, setGender] = useState();
return (
<>
<h1>Create User</h1>
<Mutation mutation={CREATE_USER}>
{(createUser, { data }) => {
console.log(createUser);
return (
<form
onSubmit={e => {
e.preventDefault();
createUser({variables : {id, name, email, age, gender}})
}}
>
*id: <input value={id} onChange={e => setId(e.target.value)} />
*name: <input value={name} onChange={e => setName(e.target.value)} />
*email:<input value={email} onChange={e => setEmail(e.target.value)} />
age: <input value={age} onChange={e => setAge(e.target.value)} />
gender:<input value={gender} onChange={e => setGender(e.target.value)} placeholder="MAN WOMAN" />
<input type="submit" />
</form>
);
}}
</Mutation>
</>
);
}
Copy the code