Reputation: 21
I'm developing a Raycast extension.
In this function, I need to create or update a database before querying it:
import { useSQL } from "@raycast/utils";
export const useSqlNote = <NoteItem>(query: string) => {
const [ready, setReady] = useState<boolean>(false);
let theData: NoteItem[] = [];
let loadingSelect = true;
let permissionVw;
useEffect(() => {
(async () => {
await create_or_update_db();
setReady(true);
})();
}, [query]);
try {
const { data, isLoading, permissionView } = useSQL<NoteItem>(PATH, query);
if (ready) {
theData = data || [];
loadingSelect = isLoading;
permissionVw = permissionView;
}
} catch (e) {}
return { data: theData, isLoading: loadingSelect, errorView: permissionVw };
};
When the database is already created, no pb.
But when it needs to be created, the process takes several ms -- and of course the call of the hook useSQL
raises an error, but it should be handled.
However, I'm getting this error:
Warning: React has detected a change in the order of Hooks called by Command.
...
Error: Rendered more hooks than during the previous render.
Any idea on how to fix it?
Upvotes: 2
Views: 178
Reputation: 2037
You are not calling the useQuery on the top level of the component. Remove the try catch block.
To conditionally call the useQuery hook, the documentation for raycast useQuery states that you can pass the options with execute param to skip the calling of the query.
"options.execute is a boolean to indicate whether to actually execute the function or not. This is useful for cases where one of the function's arguments depends on something that might not be available right away (for example, depends on some user inputs). Because React requires every hook to be defined on the render, this flag enables you to define the hook right away but wait until you have all the arguments ready to execute the function."
const { data, isLoading, permissionView } = useSQL<NoteItem>(PATH, query, {execute: ready});
//You do not need this
//if (ready) {
// theData = data || [];
// loadingSelect = isLoading;
// permissionVw = permissionView;
// }
return { data: data || [], isLoading, errorView: permissionView };
Upvotes: 1