如何使用 React 在 Apollo 客户端中交互 Query 和 Mutation

How to interact Query and Mutation in Apollo-client using React

我正在学习 Apollo 和 react-hook。我正在尝试编写一个小演示,它只输入一个名称并在下面呈现它。所有数据都是通过Apollo-server查询和变异的。

现在 Apollo 服务器可以正常工作了。但是每次输入新名称时,我都必须刷新页面。 enter image description here 我应该在react中设置状态,但我不知道如何在react中正确设置它。

代码如下:

App.js

import React, { useState } from 'react';
import './App.css';

import ShowChannel from './ShowChannel';
import AddChannel from './AddChannel';

function App() {
    return (
        <div>
            <AddChannel></AddChannel>
            <ShowChannel></ShowChannel>
        </div>
    );
}

export default App;

ShowChannel.js

import React, { useState } from 'react'
import { useQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';

const QUERY_CLIENT = gql`
    query {
        channels {
            id
            name
        }
    }
`;

export default function ShowChannel() {
    const { loading, error, data } = useQuery(QUERY_CLIENT);

    if (loading) return 'Loading...';
    if (error) return `Error! ${error.message}`;
    return (
        <div>
            <ul>
                {
                    data.channels.map((channel) => (
                        <li key={channel.id}> {channel.id}: {channel.name}</li>
                    ))
                }
            </ul>
        </div>
    )
}

AddChannel.js

import React from 'react';

import { useMutation } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';

const ADD_CHANNEL = gql`
    mutation ($name: String!){
        addChannel(name: $name){
            id
            name
        }
    }
`;

const AddChannel = () => {
    let input;
    const [addChannel, { data }] = useMutation(ADD_CHANNEL);
    return (
        <div>
            <form onSubmit={e => {
                e.preventDefault();
                addChannel({ variables: { name: input.value } });
                input.value = '';
            }}>
                <input
                    ref={node => {
                        input = node;
                    }}
                />
                <button type="submit">add channel</button>
            </form>
        </div>
    );
};

export default AddChannel;

有多种方法可以使您的数据与 UI 保持同步。

  1. 在你的突变之后调用 refetch。阅读更多 here

  2. 使用 useMutationupdate 属性在突变后更新缓存。阅读更多 here

  3. 使用Subscription跨平台保持数据同步。