Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo Client: Upsert mutation only modifies cache on update but not on create

I have an upsert query that gets triggered on either create or update. On update, Apollo integrates the result into the cache but on create it does not.

Here is the query:

export const UPSERT_NOTE_MUTATION = gql`
  mutation upsertNote($id: ID, $body: String) {
    upsertNote(id: $id, body: $body) {
      id
      body
    }
  }`

My client:

const graphqlClient = new ApolloClient({
  networkInterface,
  reduxRootSelector: 'apiStore',
  dataIdFromObject: ({ id }) => id
});

The response from the server is identical: Both id and body are returned but Apollo isn't adding new ids into the data cache object automatically.

Is it possible to have Apollo automatically add new Objects to data without triggering a subsequent fetch?

Here is what my data store looks like:

enter image description here

UPDATE

According to the documentation, the function updateQueries is supposed to allow me to push a new element to my list of assets without having to trigger my origin fetch query again.

The function gets executed but whatever is returned by the function is completely ignored and the cache is not modified.

Even if I do something like this:

    updateQueries: {
      getUserAssets: (previousQueryResult, { mutationResult }) => {
        return {};
      }
    }

Nothing changes.

UPDATE #2

Still can't get my assets list to update.

Inside updateQueries, here is what my previousQueryResult looks like:

    updateQueries: {
      getUserAssets: (previousQueryResult, { mutationResult }) => {
        return {
          assets: []
            .concat(mutationResult.data.upsertAsset)
            .concat(previousQueryResult.assets)
        }
      }
    }

But regardless of what I return, the data store does not refresh:

enter image description here

For reference, here is what each asset looks like:

enter image description here

like image 358
dipole_moment Avatar asked Jan 15 '17 20:01

dipole_moment


1 Answers

Have you followed the example here ? I would write the updateQueries in the mutate like this:

updateQueries: {
  getUserAssets: (previousQueryResult, { mutationResult }) => {
    const newAsset = mutationResult.data.upsertAsset;
    return update(prev, {
      assets: {
        $unshift: [newAsset],
      },
    });
  },  
}

Or with object assign instead of update from immutability-helper:

updateQueries: {
  getUserAssets: (previousQueryResult, { mutationResult }) => {
    const newAsset = mutationResult.data.upsertAsset;
    return Object.assign({}, prev, {assets: [...previousQueryResult.assets, newAsset]});
  },  
}
like image 175
Nima Avatar answered Sep 28 '22 05:09

Nima