skorphil / nextjs-form

Educational NextJs project to build a complex mobile-first form
https://www.chromatic.com/library?appId=65b2882ac1586a6b21cba0dd
MIT License
3 stars 0 forks source link

Scenario - submit the record #4

Closed skorphil closed 8 months ago

skorphil commented 10 months ago

What is the most appropriate way of submitting the data?

react-hook-form provides internal mechanisms for that:

They use either action or onSubmit. onSubmit fires before action is performed – form-submission-algorithm

  1. Validation is passed useForm({resolver: yupResolver(schema)})
  2. onSubmit is fired
  3. action is performed
// Use action prop to make post submission with formData
      <Form
        action="/api"
        control={control}
        onSuccess={() => {
          alert("Success")
        }}
        onError={() => {
          alert("error")
        }}
      >
        {" "}
        <input {...register("name")} />
        {isSubmitSuccessful && <p>Form submit successful.</p>}
        {errors?.root?.server && <p>Form submit failed.</p>} <button>submit</button>
      </Form>
      // Manual form submission
      <Form
        onSubmit={async ({ formData, data, formDataJson, event }) => {
          await fetch("api", {
            method: "post",

            body: formData,
          })
        }}
      >
skorphil commented 10 months ago

action described on 2:00 https://www.youtube.com/watch?v=dDpZfOQBMaU

skorphil commented 9 months ago

For this scenario it is needed to use db instead of a temporary json file.

looking for suggestion on simple DB https://www.reddit.com/r/nextjs/comments/1b4qnqg/suggestion_on_simple_database_as_an_alternative/

Mongo with nodejs https://www.mongodb.com/nodejs-database Moongose claims to simplife forking with mongodb

Small databases:

skorphil commented 9 months ago

Task intercects with

skorphil commented 9 months ago

ORM tools help to map oop app to relational db

https://www.prisma.io/nextjs

Mongoose is mapper to MongoDb

skorphil commented 9 months ago

Related materials

Use server actions with react-hook-form https://brockherion.dev/blog/posts/using-react-hook-form-with-nextjs-13-server-actions/ https://nehalist.io/react-hook-form-with-nextjs-server-actions/ https://medium.com/@danielmdob/using-next-js-server-actions-with-react-hook-form-4eadbd7f1c67

Nextjs fetching https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating

skorphil commented 9 months ago

We can invoke server Action via handleSubmit:

// servrerAction.js

'use server'

export async function getFullName({firstName, lastName}: FullName) {
  const loggedContent = `entered name: ${firstName} ${lastName}`;
  console.log(loggedContent);
  return loggedContent;
}
//form.jsx

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { getFullName } from './api';

const NameForm = () => {
  const [serverResponse, setServerResponse] = useState(null);
  const { register, handleSubmit } = useForm();

  const onSubmit = async (data) => {
    const response = await getFullName(data);
    setServerResponse(response);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col items-center space-y-2">
      <Input placeholder="First Name" {...register('firstName')} />
      <Input placeholder="Last Name" {...register('lastName')} />
...

handleSubmit() returns same as getValues() - nested object in my case onClick={formMethods.handleSubmit((data) => console.log(data) )} can invoke server action

skorphil commented 9 months ago

Server action can be invoked via <form action{getFullName}, like here: https://nehalist.io/react-hook-form-with-nextjs-server-actions/#:~:text=we%20should%20use%20the%20action%20prop

But [here](https://brockherion.dev/blog/posts/using-react-hook-form-with-nextjs-13-server-actions/#:~:text=(%0A%20%20%20%20%3Cform-,onSubmit,-%3D%7Bform) used <form onSubmit={form.handleSubmit((data) => onMyFormSubmit(data))}> IDK why but since first example reference nextjs docs i will stick to action

skorphil commented 9 months ago

Decomposition