0

Working on a react apollo graphcool project

I've got my mutation update working, however I would like to filter the results, the results only filter on page refresh?

Looking at cache.writeQuery() the docs say get the query and concat to that so i guess thats why its not filtering. Is there anyway to query after?

Here the code from my CreatePost component

import React from 'react';
import gql from "graphql-tag";
import { Mutation } from "react-apollo";

const GET_POSTS = gql`
  {
    allPosts(orderBy: createdAt_DESC) {
      id
      title
      content
    }
  }
`;

const CREATE_POST = gql`
  mutation createPost($title: String!, $content: String!){
      createPost(title: $title, content: $content){
        id  
        title
        content
      }    
    }   
`;

const udpateCache = (cache, { data: { createPost } }) => {
    const { allPosts } = cache.readQuery({ query: GET_POSTS });
    cache.writeQuery({
        query: GET_POSTS,
        data: { allPosts: allPosts.concat([createPost]) }
    })
}

const CreatePost = () => {
    //vars for the input refs
    let titleInput
    let contentInput

    return (
        <Mutation
            mutation={CREATE_POST}
            update={udpateCache}
        >
           {createPost => ( //##form and onSubmit ##// ) }
        </Mutation>
    )
}

export default CreatePost
Andrew
  • 105
  • 2
  • 9
  • Can you please clarify on your expected filtering? Using GraphQL to control your filter would require changes across multiple pieces of the stack – Benjamin Charais Sep 13 '18 at 18:37
  • The 'filtering' is actually orderBy: this is in the gql query and being sent to graphcool. the query and orderBy works on page load but not after the mutation and update={} – Andrew Sep 14 '18 at 08:50

1 Answers1

0

When you do your writeQuery you also need to pass in any variables used, to make sure you receive the same information from the cache.

const udpateCache = (cache, { data: { createPost } }) => {
    const { allPosts } = cache.readQuery({ query: GET_POSTS });
    cache.writeQuery({
        query: GET_POSTS,
        data: { allPosts: allPosts.concat([createPost]) },
        variables: { orderBy: /* input */ }
    })
}
Benjamin Charais
  • 1,248
  • 8
  • 17
  • thanks, I did try this but it won't work as there are only two args allowed in proxy.writeQuery({ query, data }); https://www.apollographql.com/docs/react/advanced/caching.html#after-mutations the orderBy is already in the 'GET_POSTS' query – Andrew Sep 17 '18 at 10:41
  • I moved on to use refetchQueries which is working, but i wanted to find a solution without having to send a req https://stackoverflow.com/questions/51695337/refetchqueries-in-mutation-component-of-react-apollo-client-is-not-working – Andrew Sep 17 '18 at 10:56