Trying to refetch the data using Apollo query - javascript

I am trying to refetch the data after an action is done but i am failing at refetching and the page is not refreshing with the data.
Below is the code for mutation and fetch queries:
const {
data: designHubProjectData,
loading: designHubProjectDataLoading,
error: designHubProjectDataError
} = useQuery(ALL_DESIGNHUB_PROJECTS, {
fetchPolicy: 'network-only',
variables: {
order: [{ projectNumber: 'DESC' }]
}
});
const [insertEmployeeDesignHubProjectBookmarkMutation] = useMutation(
INSERT_EMPLOYEE_DESIGNHUB_PROJECT_BOOKMARK,
{
refetchQueries: [ // here i am calling two queries after insert
{
query: EMPLOYEE_DESIGNHUB_PROJECT_BOOKMARK,
variables: {
order: [{ projectNumber: 'DESC' }]
}
},
{
query: ALL_DESIGNHUB_PROJECTS,
fetchPolicy: 'network-only',
variables: {
order: [{ projectNumber: 'DESC' }]
}
}
]
}
);
and then below is the method where i am calling above mutation
const handleAddBookmark = record => {
insertEmployeeDesignHubProjectBookmarkMutation({
variables: {
employeeId: loggedInEmployee.id,
projectNumber: record.projectNumber
}
}).then(({ data }) => {
if (data.insertEmployeeDesignHubProjectBookmark.ok) {
notification.success({
message: 'Success',
description: 'Successfully bookmarked the project.'
});
} else {
const errors = data.insertEmployeeDesignHubProjectBookmark.errors.join(', ');
notification.error({
message: 'Error',
description: `Adding bookmark to the project failed: ${errors}.`
});
}
});
};
i am not sure where I am doing wrong with the above code. Could any one please let me know any suggestion or ideas how to refetch make it work, many thanks in advance

I have solved this problem by assigning refetch to Oncompleted method like as below,
const {
data: designHubProjectBookmarkData,
loading: designHubProjectBookmarkDataLoading,
error: designHubProjectBookmarkDataError,
refetch: refetchBookmarkProjects
} = useQuery(EMPLOYEE_DESIGNHUB_PROJECT_BOOKMARK, {
fetchPolicy: 'network-only',
variables: {
order: { projectNumber: 'DESC' }
}
});
const [insertEmployeeDesignHubProjectBookmarkMutation] = useMutation(
INSERT_EMPLOYEE_DESIGNHUB_PROJECT_BOOKMARK,
{
onCompleted: refetchBookmarkProjects
}
);
if it incase anyone in the future looking for the same, this is an example.

Related

Why is cache.readQuery returning null?

I have a project management application built with React and GraphQL for which the Github repo can be found here. One of the functionalities allows for deleting a project.
I am trying to update the cache when I delete an individual project.
const [deleteProject] = useMutation(DELETE_PROJECT, {
variables: { id: projectId },
update(cache, { data: { deleteProject } }) {
const { projects } = cache.readQuery({ query: GET_PROJECTS });
cache.writeQuery({
query: GET_PROJECTS,
data: {
projects: projects.filter(
(project) => project.id !== deleteProject.id
),
},
});
},
onCompleted: () => navigate("/"),
});
However, when I attempt to do so, I am getting the following error: Error: Cannot destructure property 'projects' of 'cache.readQuery(...)' as it is null
Can someone help me figure out what's going on? This is what the getProjects query looks like:
const GET_PROJECTS = gql`
query getProjects {
projects {
id
name
description
status
}
}
`;
Here is the root query:
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
projects: {
type: new GraphQLList(ProjectType),
resolve(parent, args) {
return Project.find();
},
},
project: {
type: ProjectType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return Project.findById(args.id);
},
},
clients: {
type: new GraphQLList(ClientType),
resolve(parent, args) {
return Client.find();
},
},
client: {
type: ClientType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return Client.findById(args.id);
},
},
},
});

Apollo resolver chain returning undefined? Cannot read properties of undefined

I'm new to Apollo (back-end in general) so your patience is appreciated; I've looked through Apollo's docs and I'm not sure where I've gone wrong.
The data I'm receiving from my REST API call is as follows - I'm trying to return the ids and titles and based on my trials, I'm fairly certain the issue is my resolvers? The error I'm receiving is: "Cannot read properties of undefined (reading: 'session')"
{
"selection": {
...other data...
"options": [
{
id: 1
title: "Option 1 Title"
},
{
id: 2
title: "Option 2 Title"
},
]
}
}
My schema:
type Query {
session: Selection
}
type: Selection {
...other data...
optionListing: [Options]
}
type: Options {
id: Int
title: String
}
My resolvers:
{
Query: {
session: async (parent, args, {tokenAuth}) => {
...token auth code....
return tokenAuth;
};
}
Selection: {
optionListing: async ({tokenAuth}) => {
...this is the resolver that triggers the API call...
return optionData;
}
}
Options: {
id: async(parent) => {
const tempID = await parent;
return tempID.id;
}
title: async(parent) => {
const tempTitle = await parent;
return tempTitle.title;
}
}
}

Reactive queries Apollo graphql in Vue 3

Trying to make a reactive query as per https://v4.apollo.vuejs.org/guide-option/queries.html#reactive-query-definition, but I can't get them to work.
Error:
Uncaught (in promise) Error: Invalid AST Node: { query: { kind: "Document", definitions: [Array], loc: [Object] }, loadingKey: "loading" }.
Query inside export default (checked is a reactive boolean v-model'ed to a button defined in data()):
apollo: {
getTags: getTags,
getPhotos: {
query() {
if (this.checked)
return {
query: getPhotos,
loadingKey: "loading",
}
else {
return {
query: getPhotosByTag,
loadingKey: "loading",
}
}
},
update: (data) => data.getPhotos || data.getPhotos,
},
},
GQL getPhotosByTag:
const getPhotosByTag = gql`
query getPhotosByTag {
getPhotos: findTagByID(id: 326962542206255296) {
photos {
data {
name
description
_id
}
}
}
}
`
GQL getPhotos:
const getPhotos = gql`
query getPhotos {
getPhotos: getPhotos(_size: 50) {
data {
name
description
_id
}
}
}
`
If I take them out into separate queries and try to instead update use skip() via checked and !checked in the query definition, only the initial load delivers a query, if I click the button new query doesn't launch. Queries work by themselves fine.
apollo: {
getPhotos: {
query() {
return this.checked ? getPhotos : getPhotosByTag
},
loadingKey: "loading",
update: (data) => data.getPhotos || data.getPhotos,
},
},
Loading key has to be on the same level as query

apollo client offsetLimitPagination not working

I have a hook..
export function useLazyProposalList() {
const [getQueueData, { loading, data, error, fetchMore }] = useLazyQuery(PROPOSAL_LIST, {
fetchPolicy: 'no-cache',
});
const proposalList = React.useMemo(() => {
if (!data) {
return null;
}
return transformProposals(data);
}, [data]);
return {
getQueueData,
fetchMore,
loading,
data: proposalList,
error,
};
}
In the component
const {
getQueueData,
data: queueData,
fetchMore: fetchMoreProposals,
// loadMore: loadMore,
} = useLazyProposalList();
If user clicks on fetch more button, I call: fetchMoreProposals .
await fetchMoreProposals({
variables: {
offset: visibleProposalList.length,
},
});
but this doesn't update my data. I read that we should use offsetLimitPagination, but my data from query is not array itself. It's like this: queue { id: '1', items:[] } and because of this, offsetLimitPagination doesn't work. So I tried merge
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
queue: {
keyArgs: false,
merge(existing, incoming) {
console.log(existing, incoming);
if (!incoming) return existing;
if (!existing) return incoming;
},
},
},
},
}
but in the console, it just prints refs instead of real data.
What could be the issue ?

prisma2: how to fetch nested fields?

In prisma 1 I have used fragment to fetch the nested fields.
For example:
const mutations = {
async createPost(_, args, ctx) {
const user = await loginChecker(ctx);
const post = await prisma.post
.create({
data: {
author: {
connect: {
id: user.id,
},
},
title: args.title,
body: args.body,
published: args.published,
},
})
.$fragment(fragment);
return post;
},
};
but seems like in prisma2 it is not supported. because by running this on playground,
mutation CREATEPOST {
createPost(
title: "How to sleep?"
body: "Eat, sleep, repaet"
published: true
) {
title
body
published
author {
id
}
}
}
I am getting,
"prisma.post.create(...).$fragment is not a function",
The include option is used to eagerly load relations in Prisma.
Example from docs:
const result = await prisma.user.findOne({
where: { id: 1 },
include: { posts: true },
})
Assuming a user table with a one-to-many posts relation, this will return back the user object with the posts field as well.
Prisma also supports nesting as well, for example:
const result = await prisma.user.findOne({
where: { id: 1 },
include: {
posts: {
include: {
author: true,
}
},
},
})

Categories

Resources