Reputation: 13
Actually, I am a newbie to Firebase as well as to react query I can do basic stuff with them you can say that I can tell how things are working in both of them, and to a extent i can implement both averagely in projects sometimes I need help for few things and this is one of that case here I want to leverage the cache feature of tanstack query with data that I am getting through firestore manually I don't want to use a library like react query firebase or something like that I want to use it manually just for caching purpose so is there anyone who can help?
I have tried chatgpt Gemini and some amount of custom code also I searched on GitHub for some boilerplate but they are too old and I am feeling unable to understand them completely also tried to google it and got some blogs but they are either difficult to understand or you can say most of them are old
Upvotes: 1
Views: 2224
Reputation: 122
I give you an exemple with your data in the other post.
That use a function who call a query to firestore and return data
const root = ReactDOM.createRoot(document.getElementById("root"));
const queryClient = new QueryClient();
root.render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
const App = () => {
return (
<>
<Profile />
{/* other components rendered */}
</>
);
};
function Profile() {
//My custom hook that I created to access the firebase settings and all its functions that i created or are precreated
const firebase = useFirebase();
const db = firebase.firestore;
const userRef = collection(db, "users");
const userEmail = firebase.user?.email ?? null;
const queryClient = useQueryClient();
const getProfileData = async () => {
let data = { user: null, docId: null };
if (!userEmail) {
//no user
return data;
}
const query = query(userRef, where("Email", "==", userEmail));
try {
const querySnap = await getDocs(query);
if (querySnap.empty()) {
// no documents find
return data;
}
querySnap.forEach((doc) => {
data.user = doc.data();
data.docId = doc.id;
});
} catch (error) {
//I thinks if error throwed react-query catch them but may be
throw error;
}
return data;
};
//staleTime con
const { isPending, error, data } = useQuery({
queryKey: ["userInfos"],
queryFn: getProfileData,
staleTime: 10 * 60 * 1000,
initialData: () => {
return queryClient.getQueryData(["userInfos"])?.data ?? undefined;
},
});
//data loading
if (isPending) return "Loading...";
//error
if (error) return "An error has occurred: " + error.message;
//data is here
return (
<div>
<h1>{data.dsiplayName}</h1>
<p>{data.email}</p>
</div>
);
}
I thinks you need to seen video and more exemple for understand how work the caching rules and invalidation data in react query.
Upvotes: 3