Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writing to cache make an api call to fetch data. #6872

Closed
ShadabFaiz opened this issue Aug 21, 2020 · 5 comments
Closed

Writing to cache make an api call to fetch data. #6872

ShadabFaiz opened this issue Aug 21, 2020 · 5 comments

Comments

@ShadabFaiz
Copy link

Scenario:
This is my query:

export const GET_TODO_BY_ORG = gql`
	query getToDos($filter: JSON) {
		todo(where: $filter) {
			id
			name
			short_name
		}
	}
`;

This returns an array of objects containing 3 fields: name, id, short_name along with a __typename . Assume the __typename for these objects are getTODO . This is how i'm getting the data from Server:

       useQuery(GET_TODO_BY_ORG , filter);
	let cachedWorkspaces: IGET_TODO_BY_ORG | null = null;
	try {
		cachedWorkspaces = apolloClient.readQuery<IGET_TODO_BY_ORG >(
			{
				query: GET_TODO_BY_ORG ,
				variables: { ...filter.variables },
			},
			true
		);
	} catch (error) {}

Now I want to update the data in cached array.

// Mutation to create new TODO.
export const CREATE_WORKSPACE = gql`
	mutation CreateToDO($payload: createToDoInput) {
		createToDo(input: $payload) {
			todo{
				id
				name
				short_name
				description
				organization {
					id
					name
				}
			}
		}
	}
`;


let [Create_TODO, { data: response, loading, error: createError }] = useMutation<
		Create_TODO_Response,
		{ payload: { data: IGET_WORKSPACES_BY_ORG  } }
	>(CREATE_WORKSPACE, {
		onCompleted: (data) => {
			return setsuccessMessage("ToDO Created.");
		},
		update: (cache, option) => {
                      // For the sake of simplicity I have removed the logic for create a new array.
		       cache.writeQuery({
		       broadcast: true,
		       query: GET_TODO_BY_ORG ,
		       data: updatedTodoList,
		       variables: { filter: { organization: organizationId } },
	            });
		},
	});

Important point to mention here is that the __typename returned after creating a ToDo is different than the one already in cache.
Now in the array updatedTodoList, the last object contains addition keys description and organisation along with different __typename. When the cache.writeQuery is execute, the useQuery is also run making an additional unnecessary api call. If I remove the new key from the latest todo object, then no api call is made after writing into the cache.

Intended outcome:
Writing to cache should not make any api call.

Actual outcome:
Writing to cache make any api call.

How to reproduce the issue:
Mentioned in the scenario

Versions
"@apollo/client": "^3.0.2",
"graphql": "^15.3.0",

Apollo CLient Configuration

const httpLink = new HttpLink({ uri: `${process.env.REACT_APP_BASEURL}/graphql` });

const authMiddleware = new ApolloLink((operation, forward) => {
	operation.setContext(({ headers = {} }: any) => ({
		headers: {
			...headers,
			Authorization: `BEARER ${getToken()}`,
		},
	}));

	return forward(operation);
});
export const client = new ApolloClient({
	cache: new InMemoryCache(),
	link: concat(authMiddleware, httpLink),
});

@Fl0rianFischer
Copy link

Fl0rianFischer commented Aug 26, 2020

I'm experiencing the same issue. Also sometimes the data that is returned from the server overwrites my cached data. But I could not figure out yet how to reproduce this behavior, it seems very random.

Edit

@ShadabFaiz check out this comment, it'll probably solve your issue.

@Zigonja
Copy link

Zigonja commented Aug 31, 2020

I too am having this exact issue. However the integrated updating with id field works fine.

@anthonylebrun
Copy link

For what it's worth, I've resorted to this workaround:

typePolicies: {
  Query: {
    fields: {
      user: {
        merge(existing, incoming, { args }) {
          return { ...existing, ...incoming };
        },
      },
    }
  }
}

Manually specifying the merging policy seems to bypass default re-fetch behavior.

@hwillson
Copy link
Member

hwillson commented May 5, 2021

Let us know if this is still a concern with @apollo/client@latest - thanks!

@hwillson hwillson closed this as completed May 5, 2021
@mlarcher
Copy link

@hwillson Can you tell us if it the same issue that was described in #7485 by any chance ?

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 15, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants