Apollo, optimistic creation, and redirection

307 Views Asked by At

I am facing some troubles with my GraphQL optimistic rendering. I'm using Apollo Client, such as:

const history = useHistory();
const [addItem] = useMutation(ADD_ITEM_QUERY);

const onClick = () => {
    addItem({
        variables: {
            id: '16b1119a-9d96-4bc8-96a3-12df349a0c4d',
            name: 'Foo Bar'
        },
        optimisticResponse: {
            addItem {
                id: '16b1119a-9d96-4bc8-96a3-12df349a0c4d',
                name: 'Foo Bar',
                __typename: 'Item'
            }
        },
        update: () => {
            // Update item cached queries

            history.push(`/items);
        }
    });
};

The issue comes from the redirect. As far as I understand it, the update function is called twice: a first time with the optimisticResponse, and a second time with the network response (which should normally be the same).

However, let's consider the following scenario:

  1. I create a new item,
  2. I receive the optimistic response, and I'm redirected to the list of items,
  3. I click on "Add an item" to be redirected to the form
  4. I receive the server response, hence I'm redirected again to the list.

What is the correct way to prevent this double redirection?

I thought checking the current cache value. If the value is already the latest one, I won't apply the redirect. Not sure if there is a better way? How do you proceed such a scenario?

1

There are 1 best solutions below

0
On

You should call history.push outside of the update function. You can do

addItem({...}).then(() => history.push('/items')).