Skip to content

Commit

Permalink
extract update recipe mutation into custom hook
Browse files Browse the repository at this point in the history
  • Loading branch information
michalparkola committed Sep 25, 2024
1 parent 98c796c commit 0079369
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
17 changes: 5 additions & 12 deletions screens/recipes/Recipe.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import React from "react";
import { View, ScrollView, Text } from "react-native";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { getNugget, updateNugget } from "@/supabase/supabase-queries";
import { useQuery } from "@tanstack/react-query";
import { useUpdateRecipe } from "./useUpdateRecipe";
import { getNugget } from "@/supabase/supabase-queries";
import { gs } from "@/global-styles";
import EditableTextInputWithCancelSave from "@/components/EditableTextInputWithCancelSave";
import { Tables } from "@/supabase/database.types";
import EditableTODOSwitch from "@/components/EditableTODOSwitch";

interface Props {
nugget_id: string;
}

export default function Recipe({ nugget_id }: Props) {
const queryClient = useQueryClient();

// Query: nugget_id
const {
data: nugget,
Expand All @@ -24,13 +22,7 @@ export default function Recipe({ nugget_id }: Props) {
queryKey: ["nugget", nugget_id],
});

const updateNuggetMutation = useMutation({
mutationFn: (new_nugget: Tables<"Nuggets">) => updateNugget(new_nugget),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["nugget", nugget_id] });
queryClient.invalidateQueries({ queryKey: ["nuggets"] });
},
});
const updateNuggetMutation = useUpdateRecipe(Number(nugget_id));

if (isPending) return <Text>Loading recipe...</Text>;
if (error)
Expand All @@ -41,6 +33,7 @@ export default function Recipe({ nugget_id }: Props) {
);
return (
<ScrollView contentContainerStyle={{ margin: 12 }}>
<Text style={gs.label}>Shelved</Text>
<EditableTODOSwitch
is_todo={nugget.is_todo}
handleToggle={() => {
Expand Down
16 changes: 16 additions & 0 deletions screens/recipes/useUpdateRecipe.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useQueryClient, useMutation } from "@tanstack/react-query";
import { updateNugget } from "@/supabase/supabase-queries";
import { Tables } from "@/supabase/database.types";

export function useUpdateRecipe(nugget_id: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (new_nugget: Tables<"Nuggets">) => updateNugget(new_nugget),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["nugget", nugget_id],
});
queryClient.invalidateQueries({ queryKey: ["nuggets"] });
},
});
}

0 comments on commit 0079369

Please sign in to comment.