Реагировать на Apollo клиентский prop refetchQueries после мутации - PullRequest
0 голосов
/ 12 сентября 2018

Я читаю документацию Apollo и не могу найти примеров того, как выполнить повторную выборку после мутации с реквизитом client, который передается withApollo HOC.

Мой компонент:

import React, {Fragment} from 'react';
import gql from 'graphql-tag';
import { withApollo } from 'react-apollo';
...

const getPosts =  gql`
{
    posts {
    _id
    title
    description
    user {
        _id
    }
  }
}`;


const deletePost = gql`
    mutation deletePost($_id: String){
        deletePost(_id: $_id)
    }
`;

class PostList extends React.Component {
    static propTypes = {
        match: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired,
    };
    state = {posts: null};

    componentDidMount() {
        this.props.client.query({
                query: getPosts,
            }).then(({ data }) => {
                this.setState({ posts: data.posts });
            });
    }

    deletePost = postId => {
        this.props.client
            .mutate({
                mutation: deletePost,
                variables: {
                    _id: postId
                },
            })
            .then(({ data }) => {

                alert('Post deleted!');
            });
    };


    render() {
        const {posts} = this.state;    
        if (!posts) {
            return <div>Loading....</div>
        }

        return (
            <div className="post">
                ...stuff...
            </div>
        )
    }
}

export default withApollo(PostList);

Я хочу обновлять сообщения при каждом их удалении.

1 Ответ

0 голосов
/ 12 сентября 2018

Данные posts, которые вы выводите, находятся в состоянии вашего компонента, но вы запрашиваете сообщения только в componentDidMount. Этот метод вызывается только при первом отображении компонента.

class PostList extends React.Component {

    fetchPosts() {
        this.props.client.query({
                query: getPosts,
            }).then(({ data }) => {
                this.setState({ posts: data.posts });
            });
    }

    componentDidMount() {
        this.fetchPosts();
    }

    deletePost = postId => {
        this.props.client
            .mutate({
                mutation: deletePost,
                variables: {
                    _id: postId
                },
            })
            .then(({ data }) => {
                this.fetchPosts()
            });
    };


    render() {
        const {posts} = this.state;    
        if (!posts) {
            return <div>Loading....</div>
        }

        return (
            <div className="post">
                ...stuff...
            </div>
        )
    }
}

На самом деле вам даже не нужно иметь локальное состояние, вы можете положиться на локальный кеш клиента Apollo и использовать компонент Query , а также компонент Mutation .

...