Wait for useQuery result

const favShop = trpc.favorite.getById.useQuery({
userId: session.data?.user?.id,
shopId: coffeeShop.id,
})

const [favorite, setFavorite] = useState(
favShop.data?.length !== 0 && favShop.data !== undefined ? true : false
)
const favShop = trpc.favorite.getById.useQuery({
userId: session.data?.user?.id,
shopId: coffeeShop.id,
})

const [favorite, setFavorite] = useState(
favShop.data?.length !== 0 && favShop.data !== undefined ? true : false
)
so im checking on load if the current shop is a favourite shop or not, but the favShop is undefined at load then you get the result, since i cant use async await on it, how do i wait for the result so i can use it in the useState
8 Replies
batata
batataOP2y ago
this is how the value of favShop changes on load
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
batata
batataOP2y ago
im using the state for later i only wanna call the procedure on the first load
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
batata
batataOP2y ago
no im not storing the data in a state, in just checking if the object is empty or not. i used useEffect
useEffect(() => {
if (favShop.status === 'success') {
setFavorite(favShop.data?.length !== 0 ? true : false)
}
}, [favShop.data])
useEffect(() => {
if (favShop.status === 'success') {
setFavorite(favShop.data?.length !== 0 ? true : false)
}
}, [favShop.data])
so i need to wait for the status to be success thats how you know the query finished executing and this is the state
const [favorite, setFavorite] = useState(false)
const [favorite, setFavorite] = useState(false)
Neto
Neto2y ago
you also can
const [favorite, setFavorite] = useState(false)

const favShop = trpc.favorite.getById.useQuery({
userId: session.data?.user?.id,
shopId: coffeeShop.id,
}, {
onSuccess: (data) => {
setFavorite(data.length !== 0)
}
})
const [favorite, setFavorite] = useState(false)

const favShop = trpc.favorite.getById.useQuery({
userId: session.data?.user?.id,
shopId: coffeeShop.id,
}, {
onSuccess: (data) => {
setFavorite(data.length !== 0)
}
})
and every time onSuccess is called, favorite is updated
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
batata
batataOP2y ago
ohh cool didnt know i could do this yeah thats what i thought, didnt like that i used the useEffect will read it! thank youu
Want results from more Discord servers?
Add your server