I'm developing a personal project using Ionic Framework, React, and Supabase DB.
I was trying to get my clothing categories from the DB and was using showLoading() and hideLoading() during query execution.
The problem is that while fetching Menu the hideLoading() is not working, and the spinner spins forever. Another thing I noticed is that while using useEffect() hook to make the fetch function work it activates two times while loading the page, but the second useEffect executes perfectly, and so does the Loading event.
The main objective is to build the menu, add an OnClick() function that changes the father variable to the id of the menu page, and then fetch the categories associated with that page.
Here is my code:
const fetchMenu = async () => {
try {
const { data: menuData, error } = await supabase.from('categoria').select('*').eq('pai', 0);
if (error) throw error;
setMenu(menuData);
console.log(menuData);
} catch (error: any) {
await showToast({ message: error.message || error.error_description, duration: 5000 });
}
}
const fetchCategories = async (father: number) => {
showLoading();
try {
const { data: categoriesData, error } = await supabase.from('categoria').select('*').eq('pai', father);
if (error) throw error;
setCategories(categoriesData);
console.log(categoriesData);
} catch (error: any) {
await showToast({ message: error.message || error.error_description, duration: 5000 });
}
hideLoading();
}
useEffect(() => {
fetchMenu();
}, []);
useEffect(() => {
if (father != null){
fetchCategories(father);
}
}, [father]);
return (
<IonPage>
{/*CABEÇALHO*/}
<IonHeader>
<IonToolbar>
<IonTitle>Fossil Fashion</IonTitle>
</IonToolbar>
<IonSegment>
{menu?.map((menuPage: any) => (
<IonSegmentButton key={menuPage.id} value={Number(menuPage.id)} onClick={(e) => setFather(Number(e.currentTarget.value))}>
<IonLabel>{menuPage.nome}</IonLabel>
</IonSegmentButton>
))}
</IonSegment>
</IonHeader>
{/*CORPO*/}
<IonContent>
<IonSearchbar placeholder="Pesquisa"></IonSearchbar>
<IonGrid>
{categories?.map((category: any) => (
<IonRow key={category.id}>
<IonItemGroup>
<IonItemDivider>
<IonLabel>{category.nome}</IonLabel>
</IonItemDivider>
</IonItemGroup>
</IonRow>
))}
</IonGrid>
I tried using finally statment, setTimeOut function, but nothing worked.
You shoudl try this it will helpful
try and catch method doesn't block the JS thread, that's why executing of function is not working as your expectation.