defer useList load

Hi, I'm using a code like this one const [p, setP] = useState({}) const { isLoading, data } = useList(p); useEffect(() => { if (identity?.role === 'admin') { setP({ resource: "retailers", filters: [ { field: "context", operator: "eq", value: "search" }, { field: "sortOrder", operator: "eq", value: "name" } ] }) } }, [identity?.role]) The logic is that I need to load those retailers with useList only if the role is admin The problem is that, as soon as the page loads, refine useList loads the endpoint with empty parameters, as the useList is outside the useEffect BUT I cannot put the useList hook inside an useEffect as I'm getting a conditional hook error... how could I solve?
3 Replies
kapa.ai
kapa.ai3w ago
Hi @simoneb. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the knowledge sources provided, there isn't specific information about deferring the loading of useList. However, I can suggest an approach that aligns with Refine's patterns and React best practices to address your issue. Instead of using useState and useEffect to conditionally set the parameters, you can use the enabled option in the queryOptions of useList. This approach allows you to control when the query should run. Here's how you can modify your code:
const { data, isLoading } = useList({
resource: "retailers",
filters: [
{
field: "context",
operator: "eq",
value: "search"
},
{
field: "sortOrder",
operator: "eq",
value: "name"
}
],
queryOptions: {
enabled: identity?.role === 'admin'
}
});
const { data, isLoading } = useList({
resource: "retailers",
filters: [
{
field: "context",
operator: "eq",
value: "search"
},
{
field: "sortOrder",
operator: "eq",
value: "name"
}
],
queryOptions: {
enabled: identity?.role === 'admin'
}
});
In this approach: 1. We define the resource and filters directly in the useList call. 2. We use the queryOptions.enabled property to control when the query should run. It will only run when identity?.role === 'admin' is true. This solution avoids the need for a separate useState and useEffect, and prevents the initial load with empty parameters. The query will only be executed when the role is 'admin'. Remember that useList is an extended version of TanStack Query's useQuery, so it supports all of its features, including the enabled option as mentioned in the Refine documentation. This approach should solve your issue of conditional loading without running into the conditional hook error. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@539513465103056900> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
metropolitan-bronze
metropolitan-bronzeOP3w ago
this is actually the answer, thanks. I missed that part in the documentation

Did you find this page helpful?