1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-07-19 21:29:40 +02:00
mealie/frontend/composables/recipes/use-recipe-search.ts
Hoa (Kyle) Trinh c24d532608
feat: Migrate to Nuxt 3 framework (#5184)
Co-authored-by: Michael Genson <71845777+michael-genson@users.noreply.github.com>
Co-authored-by: Kuchenpirat <24235032+Kuchenpirat@users.noreply.github.com>
2025-06-19 17:09:12 +00:00

70 lines
1.6 KiB
TypeScript

import { watchDebounced } from "@vueuse/core";
import type { UserApi } from "~/lib/api";
import type { ExploreApi } from "~/lib/api/public/explore";
import type { Recipe } from "~/lib/api/types/recipe";
export interface UseRecipeSearchReturn {
query: Ref<string>;
error: Ref<string>;
loading: Ref<boolean>;
data: Ref<Recipe[]>;
trigger(): Promise<void>;
}
/**
* `useRecipeSearch` constructs a basic reactive search query
* that when `query` is changed, will search for recipes based
* on the query. Useful for searchable list views. For advanced
* search, use the `useRecipeQuery` composable.
*/
export function useRecipeSearch(api: UserApi | ExploreApi): UseRecipeSearchReturn {
const query = ref("");
const error = ref("");
const loading = ref(false);
const recipes = ref<Recipe[]>([]);
async function searchRecipes(term: string) {
loading.value = true;
const { data, error } = await api.recipes.search({
search: term,
page: 1,
orderBy: "name",
orderDirection: "asc",
perPage: 20,
_searchSeed: Date.now().toString(),
});
if (error) {
console.error(error);
loading.value = false;
recipes.value = [];
return;
}
if (data) {
recipes.value = data.items;
}
loading.value = false;
}
watchDebounced(
() => query.value,
async (term: string) => {
await searchRecipes(term);
},
{ debounce: 500 },
);
async function trigger() {
await searchRecipes(query.value);
}
return {
query,
error,
loading,
data: recipes,
trigger,
};
}