I tried to make code using initialData, but none of the output comes out even the key doesn’t appear in react-query-dev-tool
enter image description here
import { useQuery, useQueryClient } from 'react-query';
import axios from 'axios';
interface CustomError {
message: string;
}
interface User {
id: number;
first_name: string;
last_name: string;
email: string;
gender: string;
ip_address: string;
description: string;
location: string;
password: string;
mac_address: string;
url: string;
}
export async function fetchUserDataById({ queryKey }: any): Promise<User> {
const dataId = queryKey[1]
const response = await axios.get<User>(`http://localhost:5000/users/${dataId}`);
return response.data;
}
export const useDataUserById = (id: number) => {
const queryClient = useQueryClient();
return useQuery<User, CustomError>(['user-data', id], fetchUserDataById, {
initialData: () => {
const users = queryClient.getQueryData<User[]>('one-data');
if (users) {
const dataUser = users?.find((userData) => userData.id === id);
if(dataUser){
console.log(dataUser)
return dataUser
}
}
return undefined;
},
});
};
solve the problem why my initialData on react-query does’nt work
>Solution :
It looks like you need to check the query key or data structure, there’s might be a mismatch and make sure to check if the initial data you’re trying to retrieve using queryClient.getQueryData has been successfully cached in the queryClient.
you can add logs to debug each process.
export const useDataUserById = (id: number) => {
const queryClient = useQueryClient();
return useQuery<User, CustomError>(['user-data', id], fetchUserDataById, {
initialData: () => {
// Debugging: Check the key you're using for initial data retrieval
console.log("Initial data query key:", 'one-data');
const users = queryClient.getQueryData<User[]>('one-data');
// Debugging: Log the retrieved users data
console.log("Retrieved users data:", users);
if (users) {
const dataUser = users.find((userData) => userData.id === id);
if (dataUser) {
// Debugging: Log the found dataUser
console.log("Found dataUser:", dataUser);
return dataUser;
}
}
return undefined;
},
});
};