Daniel Guedes
Daniel Guedes

Reputation: 837

Get data back when successfully mutated (react-use-form, trpc and prisma)

Currently I have a form with a text input "title". When I submit the form, I can access this property via the submit handler inside my component, like this:

const formSubmit: SubmitHandler<FormSchemaType> = (formData) => {
    
    const { title } = formData;
...

and in the form:

<form
    onSubmit={handleSubmit(formSubmit)}
>
         <input
            {...register("title")}
            type="text"
          />
...

(obs: I'm aware can also use the watch() function from useForm from react-hook-form as well to have access to this fields)

All is good, but when I submit I want to look at my sqlite database from prisma and see if this title is already in there, if it is, I want to save that on a variable, and if not, I want to do a mutation to include this on my database as a title model object (type Title - which has an id and a title String) and then save that into a variable as well. But I'm struggling to find a way to do this. Here's the code and all the ways I've tried:

  ...
  import {type Title} from "@prisma/client"
  ...

  const titlesQuery = api.edit.getTitles.useQuery();
  const titlesMutation = api.edit.newTitle.useMutation();


  let savedTitle: Title | undefined; //try#1
  //const [savedTitle, setSavedTitle] = useState<Title>(); //try#2

  const formSubmit: SubmitHandler<FormSchemaType> = (formData) => {
    
    const { title } = formData;

    const possibleTitle = titlesQuery.data?.find((t) => t.title === title);
    if (!possibleDate) {
      titlesMutation.mutate(title, { //this is working - title is going to database if its not already there
        onSettled: (newTitle) => {
           console.log(newTitle); //this is logging the right thing
           savedTitle = newTitle //try#1.1
        //onSuccess: (newTitle) => savedTitle = newTitle //try#1.2
        //onSuccess: () => setSavedTitle(await datesQuery.refetch()) //try#2
      });
    } else {
      savedTitle = possibleTitle; //try#1
      //setSavedTitle(possibleTitle); //try#2
    }
console.log(savedTitle); //this is logging a title object only when the 'else' is met, more precisely, only in the case that mutation doesnt occur.

The problem, as I written above, is that I am not capable of saving this newTitle into a variable savedTitle after I do the mutation. It logs right when I log it on the "onSuccess" or "onSettled" methods, but doesnt save it to the variable, using state or not.

Please help! What can I do?

Upvotes: 0

Views: 1690

Answers (1)

user21380424
user21380424

Reputation: 16

Try titlesMutation.data. Just console.log titlesMutation and you'll see what kind of props it has, one of those is data which contains the returned value

Upvotes: 0

Related Questions