T
TanStack11mo ago
adverse-sapphire

Using react/query for non-async/global store.

Hey all I am attempting to use React Query to store some positions I am calculating onLayout.
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

export const useGetLinePositionById = ({ id }: { id: string }) => {
return useQuery({
queryKey: ["line_positions", id],
initialData: [],
});
};

export const useSetLinePositions = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (data: any) => {
return data;
},

onSuccess: (data) => {
queryClient.setQueryData(["line_positions", data.id], (old) => {
console.log("data", data);
return data.line_positions;
});
},
});
};
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

export const useGetLinePositionById = ({ id }: { id: string }) => {
return useQuery({
queryKey: ["line_positions", id],
initialData: [],
});
};

export const useSetLinePositions = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (data: any) => {
return data;
},

onSuccess: (data) => {
queryClient.setQueryData(["line_positions", data.id], (old) => {
console.log("data", data);
return data.line_positions;
});
},
});
};
I can see in my log, I am getting the data correctly in my mutation, but my query in my component is not being updated
const { data: linePositions } = useGetLinePositionById({ id: id as string });

console.log('linePositions', linePositions) // logs []
const { data: linePositions } = useGetLinePositionById({ id: id as string });

console.log('linePositions', linePositions) // logs []
any ideas? Thanks for looking!
2 Replies
fascinating-indigo
fascinating-indigo11mo ago
@zorro1rr Can you see the data in query cache from devtools ?
unwilling-turquoise
unwilling-turquoise11mo ago
The only reason why this can happen is you are updating the query data for some other query key and not the query key you want. You can look at the dev tools to see if the data that is being logged is not being set to some other query key, maybe ["line_positions", undefined] idk or maybe some different second param(id).

Did you find this page helpful?