Skip to content

Instantly share code, notes, and snippets.

@kenmori
Last active April 25, 2019 08:28
Show Gist options
  • Save kenmori/3b40539e9b02bc2cc3468626d114ad8f to your computer and use it in GitHub Desktop.
Save kenmori/3b40539e9b02bc2cc3468626d114ad8f to your computer and use it in GitHub Desktop.
[react-apollo] mutationを叩いたら他の場所にあるqueryをrefetchして値を同期させる

add fetchPolicy="cache-and-network"を追加

const Noti = () => (
  <Query query={unreadMessagesQuery} fetchPolicy="cache-and-network">
    {({ data, loading, error }) => {
      if(loading) return <LoadView />;
      if (error) return <Error />;
      return (<span className="notificationIcon">{data.unreadMessages.count}</span>);
    }}
  </Query>
);

add refetchQueries: () => [{query: unreadMessagesQuery}]

const MyPageMessageDetail = (props) => {
  useEffect(() => {
    (async () => {
      const { data } = await props.client.query({ query: messageQuery, variables: { id: props.match.params.id } });
      const shouldCallMutationForDoneRead = data.messages.nodes.map(e => e.id);
      shouldCallMutationForDoneRead.forEach(e => {
          props.client.mutate({ mutation: readMessageMutation, variables: { messageId: e }, refetchQueries: () => [{query: unreadMessagesQuery}] }).then(() => {
          });
      });
    })();
  }, []);
  return (
    <>

see: apollographql/apollo-client#3633 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment