1
votes

I have been reading the Apollo documentation and I can't find any examples on how to refetch after a mutation with the client props that is being passed by withApollo HOC.

My component:

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);

I want to refetch the posts each time one is deleted.

1

1 Answers

0
votes

The posts data that you render is in your component state, but you only query posts in componentDidMount. This method is called only when your component is first rendered.

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>
        )
    }
}

In fact, you do not even need to have a local state, you can rely on Apollo client local cache and use the Query component as well as the Mutation component.