Pranesh Ravi
Pranesh Ravi

Reputation: 19113

How to force update data cache in react-apollo?

How to refetch fresh data when you revisit a page whose data is powered by react-apollo?

Say, I visit a listing page for the first time. apollo will fetch the query and caches it by default. So, when you visit the same page again during the session, it will populate the data from its cache store. How to force apollo to refetch data every time when the component mounts?

Upvotes: 8

Views: 14111

Answers (3)

Yuci
Yuci

Reputation: 30079

In case you are using react-apollo's Query component, for example:

import { Query } from "react-apollo";

You can apply the fetchPolicy through its props. See below an example:

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

const CounterView = ({ counter }) => (
  <div>{counter}</div>
);

const GET_COUNTER = gql`
  {
    counter
  }
`;

const Counter = () => (
  <Query query={GET_COUNTER} fetchPolicy={'network-only'}>
    {({ data }) => {
      return <CounterView {...data} />;
    }}
  </Query>
);

export default Counter;

References:

Upvotes: 3

Ricardo Portugal
Ricardo Portugal

Reputation: 329

Adding to Pranesh's answer: the fetchPolicy you're looking for is network-only.

Upvotes: 9

Pranesh Ravi
Pranesh Ravi

Reputation: 19113

You can use apollo's fetchPolicy. Based on this, it will decide to execute the query or not again.

Example:

const graphQLOptions = {
  name: 'g_schemas',
  options: (props) => {
    return {
      variables: {
        name: props.name,
      },
      fetchPolicy: 'cache-and-network',
    }
  },
}

Hope it helps.

Upvotes: 10

Related Questions