T
TanStack3y ago
adverse-sapphire

useQuery triggers before calling it?

Hi again, so I have a login function that takes some credentials and then passes it to a login mutation that send it to a "/login" endpoint, after that I extracted the "isLoading" property from the mutation and I use it for the query that gets the user, the thing is I want to make the query enabled only when that property is true. => Here is that line of code: enabled: !isLoading But the query seems to trigger first thing when I get into the page, I tried making all the refetch properties to false like "refetchOnWindowFocus", "retry", "refretchInterval" and so on but it doesn't work. Any tips guys 🙏
4 Replies
useful-bronze
useful-bronze3y ago
The isLoading property on the useMutation hook is really for indication that a mutation is being run. So when the page loads, the loading flag will be set to false since the mutation isn't running. So according to the condition you set (enabled: !isLoading), the query will be enabled when the value of isLoading is falsey. This might be better.
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false)

const loginMutation = useMutation({
// ...
onSuccess: () => {
setIsLoggedIn(true)
}
})

const userQuery = useQuery({
/// ...
enabled: isLoggedIn
})

return ...
}
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false)

const loginMutation = useMutation({
// ...
onSuccess: () => {
setIsLoggedIn(true)
}
})

const userQuery = useQuery({
/// ...
enabled: isLoggedIn
})

return ...
}
adverse-sapphire
adverse-sapphireOP3y ago
is there no way to do it without using the useState hook, like with something built-in react query?
ambitious-aqua
ambitious-aqua3y ago
enabled: isSuccess where isSuccess comes from useMutation
adverse-sapphire
adverse-sapphireOP3y ago
OK I'll try it right now believe me, i tried it before and it didn't work, and now when you told to do it, it miraculously worked 😂 , many thanks!! thanks to you too sean for you suggestion 🙏

Did you find this page helpful?