T
TanStack3y ago
continuing-cyan

How To use useQuery with dependency array ?

Hello guys, I'm trying to convert this useEffect to useQuery. I have some issues with the dependency array. can some one help to slove this problem ? useEffect(() => { let isActive = true; if (!loading) setLoading(true); async function fetchData() { const { data, error } = await supabase .from("team_users") .select( team_id( project:project_team_id_fkey( id, name, is_archived, description, url, status ), name, id ) ) .match({ user_id: session.user.id }); // const { data, error } = await supabase.from('team').select(*) if (error) { console.log(error); } else { console.log(data); if (isActive) { console.log(data) setHomeData([...data]); } } } fetchData().finally(() => { setLoading(false); console.log("Api Called"); }); return () => { isActive = false; }; }, [NewPCreated, projectAchieving, refetchHomeData]);
1 Reply
metropolitan-bronze
metropolitan-bronze3y ago
// fetch function
async function fetchData({id, name, is_archived, description, url, status, session }: IUseGetTeam) {
const response = await supabase.from('team')
.select(
team_id(
project:project_team_id_fkey(
id,
name,
is_archived,
description,
url,
status
),
name,
id
)
)
.match({ user_id: session.user.id });
}

// useQuery hook
const useGetTeam = ({
id,
name,
is_archived,
description,
url,
status,
session,
}: IUseGetTeam) => {
return useQuery(
['team', {id, name, is_archived, description, url, status, session}], // queryKey
async () => await fetchData({id, name, is_archived, description, url, status, session}), // queryFn
{
enabled: !!session?.user?.id && !!id && !!name && !is_archived && !!description && !!url && !!status, // If these values are falsy, the query will not execute
}
)
}

// use it in your component like so
const {data, error, isLoading, isSuccess } = useGetTeam({
id,
name,
is_archived,
description,
url,
status,
session,
})
// fetch function
async function fetchData({id, name, is_archived, description, url, status, session }: IUseGetTeam) {
const response = await supabase.from('team')
.select(
team_id(
project:project_team_id_fkey(
id,
name,
is_archived,
description,
url,
status
),
name,
id
)
)
.match({ user_id: session.user.id });
}

// useQuery hook
const useGetTeam = ({
id,
name,
is_archived,
description,
url,
status,
session,
}: IUseGetTeam) => {
return useQuery(
['team', {id, name, is_archived, description, url, status, session}], // queryKey
async () => await fetchData({id, name, is_archived, description, url, status, session}), // queryFn
{
enabled: !!session?.user?.id && !!id && !!name && !is_archived && !!description && !!url && !!status, // If these values are falsy, the query will not execute
}
)
}

// use it in your component like so
const {data, error, isLoading, isSuccess } = useGetTeam({
id,
name,
is_archived,
description,
url,
status,
session,
})

Did you find this page helpful?