T
TanStack2mo ago
unwilling-turquoise

Using Tanstack Query for the Update page on CRUD operations

Hi, I'm looking to shift my application from using regular fetch to tanstack query and looking to update my CRUD pages. For a create operation this is more straight forward but I'm curious what sort of pattern people use with tanstack query since this has generally eliminated the need for my query to be within useEffect with. Previously I would have just done my operation inside a useEffect block which uses the set functions from useState to set the values to be displayed in
useEffect(() => {
const fetchData = async () => {
const pickemClient = PickemApiClientFactory.createClient();
const league = await pickemClient.getLeagueByIdWithUserMapping(leagueId);
setLeagueName(league.name);
// Extra properties set here
}

fetchData();
}, []);
useEffect(() => {
const fetchData = async () => {
const pickemClient = PickemApiClientFactory.createClient();
const league = await pickemClient.getLeagueByIdWithUserMapping(leagueId);
setLeagueName(league.name);
// Extra properties set here
}

fetchData();
}, []);
Is there a better/cleaner way to accomplish this using tanstack query, which has previously eliminated a lot of need for my app to have useEffect?
1 Reply
optimistic-gold
optimistic-gold4w ago
Ya you would do more like this:
// You can probably create the client outside the component just once
const pickemClient = PickemApiClientFactory.createClient()

function MyLeaguePage(leagueId) {
const { data, isPending } = useQuery({
queryKey: ['league', leagueId],
queryFn: async () => await pickemClient.getLeagueByIdWithUserMapping(leagueId)
})
return isPending ? <>Loading...</> : ...
}
// You can probably create the client outside the component just once
const pickemClient = PickemApiClientFactory.createClient()

function MyLeaguePage(leagueId) {
const { data, isPending } = useQuery({
queryKey: ['league', leagueId],
queryFn: async () => await pickemClient.getLeagueByIdWithUserMapping(leagueId)
})
return isPending ? <>Loading...</> : ...
}

Did you find this page helpful?