Cookie Consent by Free Privacy Policy Generator 📌 Building a CRUD App with Next.js, React Query, React Hook Form, and Yup

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



📚 Building a CRUD App with Next.js, React Query, React Hook Form, and Yup


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

In this tutorial, you will learn how to build a CRUD (create, read, update, delete) app using Next.js, React Query, React Hook Form, and Yup.

You will learn how to use these tools to build a CRUD app that allows users to create, read, update, and delete items stored on a server. You will also learn how to use React Query to fetch and cache data, React Hook Form to manage forms, and Yup to validate form data.

Next.js

Next.js is a framework for building server-rendered React applications. It provides features such as automatic code splitting, optimized performance, and simple client-side routing.
For more information visit NextJs

ReactQuery

React Query is a library for fetching, caching, and updating asynchronous data in React apps. It is designed to be easy to use, lightweight, and intuitive, and it can help improve the performance and user experience of your app by reducing the number of network requests and optimizing the caching of data.
For more information visit React Query

React Hook Form

React Hook Form is a library for managing forms in React apps. It provides a simple and flexible API for handling form validation, submission, and other common form tasks, and it is designed to be easy to use with React functional components and the React Hooks API.
For more information visit https://react-hook-form.com/

Yup

Yup is a JavaScript object schema validator and object parser. It provides an easy-to-use, expressive, and powerful way to validate and transform data.

You can use Yup with React Hook Form to provide more advanced validation for your forms. To use Yup with React Hook Form, you can pass a Yup validation schema to the validationSchema option of the useForm hook.
For more information visit Yup Validator

Tutorial

First, let's set up our component for creating a new item. We'll use React Hook Form and Yup to handle form validation and submission:

import { useForm } from 'react-hook-form'
import * as Yup from 'yup'

const validationSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
})

/* Create Item Form */
function CreateItemForm() {

  /* Hooks */
  const { handleSubmit, register, errors } = useForm({
    validationSchema,
  })

  /* HandleOnSubmit */
  const onSubmit = async (data) => {
    try {
      const res = await fetch('/api/items', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      const newItem = await res.json()
      console.log(newItem) 
      // log the newly created item to the console
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">Name:</label>
      <input
        name="name"
        ref={register}
      />
      {errors.name && <span>{errors.name.message}</span>}
      <br />
      <button type="submit">Create Item</button>
    </form>
  )
}

In the above CreateItemForm component, we define a Yup validation schema that requires the name field to be filled out. We pass this validation schema to the useForm hook, and then use the errors object that is returned by the hook to display error messages to the user if the form is invalid.

Next, let's set up a component for reading a list of items. We'll use React Query to fetch the list of items from the server and cache the result:

import { useQuery } from 'react-query'

/* Fetch List of Items */
function ItemList() {
  const { data, error } = useQuery('items', () => 
    fetch('/api/items').then((res) => res.json())
  )

  if (error) return <div>Error: {error.message}</div>
  if (!data) return <div>Loading...</div>

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  )
}

Now let's set up a component for updating an item. We'll again use React Hook Form and Yup to handle form validation and submission, and React Query to fetch the item data and update the cache when the item is successfully updated:

import { useForm } from 'react-hook-form'
import { useQuery, useMutation } from 'react-query'
import * as Yup from 'yup'

const validationSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
})

/* Update Item Form */
function UpdateItemForm({ itemId }) {

  const { data: item, isLoading, error } = useQuery(
    ['item', itemId],
    () => fetch(`/api/items/${itemId}`).then((res) => res.json())
  )

  const [updateItem, { isUpdating }] = useMutation(async (data) => {
    const res = await fetch(`/api/items/${itemId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    })
    return res.json()
  })

  const { handleSubmit, register, errors } = useForm({
    defaultValues: { name: item.name },
    validationSchema,
  })

  const onSubmit = async (data) => {
    try {
      const updatedItem = await updateItem(data)
      console.log(updatedItem) // log the updated item to the console
    } catch (error) {
      console.error(error)
    }
  }

  if (error) return <div>Error: {error.message}</div>
  if (isLoading) return <div>Loading...</div>

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">Name:</label>
      <input
        name="name"
        ref={register}
      />
      {errors.name && <span>{errors.name.message}</span>}
      <br />
      <button type="submit" disabled={isUpdating}>
        Update Item
      </button>
    </form>
  )
}

In the UpdateItemForm component, we define a **Yup validation schema **that requires the name field to be filled out. We pass this validation schema to the useForm hook, and then use the errors object that is returned by the hook to display error messages to the user if the form is invalid.

Finally, let's set up a component for deleting an item. We'll use React Query's useMutation hook to send a DELETE request to the server and update the cache when the item is successfully deleted:

import { useMutation } from 'react-query'

function DeleteItemButton({ itemId }) {
  const [deleteItem, { isDeleting }] = useMutation(async () => {
    const res = await fetch(`/api/items/${itemId}`, {
      method: 'DELETE',
    })
    return res.json()
  }, {
    onSuccess: () => {
      console.log('Item deleted!') 
      // log a success message to the console
    },
  })

  return (
    <button onClick={deleteItem} disabled={isDeleting}>
      Delete Item
    </button>
  )
}

useMutation (React Query)

useMutation is a hook provided by the react-query library that allows you to execute mutations (such as creating, updating, or deleting data) in your application. It returns an array with two elements: the mutation function, and an object containing the status of the mutation (e.g. loading, error, or success).

A simple example of how you might use useMutation:

import { useMutation } from 'react-query';

const [createUser, { status: createStatus }] = useMutation(
  async (formData) => {
    const response = await fetch('/api/users', {
      method: 'POST',
      body: JSON.stringify(formData),
    });
    return response.json();
  },
  {
    onSuccess: () => {
      console.log('User created successfully');
      refetch();
    },
  }
);

In this example, the createUser function is used to execute the mutation by sending a POST request to the /api/users endpoint. The createStatus variable contains the status of the mutation (e.g. loading, error, or success). The onSuccess option is used to specify a callback function that will be executed when the mutation is successful.

useQuery (React Query)

useQuery is another hook provided by the react-query library that allows you to fetch data in your application. It returns an object containing the data, a flag indicating whether the data is currently being fetched, an error object if an error occurred, and a function for refetching the data.

Example of how you might use useQuery:

import { useQuery } from 'react-query';

const { data: users, isLoading, error, refetch } = useQuery('users', async () => {
  const response = await fetch('/api/users');
  return response.json();
});

if (isLoading) return 'Loading...';
if (error) return 'An error occurred';

Here, the useQuery hook is used to fetch a list of users from the /api/users endpoint. The data property of the returned object contains the fetched data, the isLoading flag is true while the data is being fetched, and the error object contains any error that occurred. The refetch function can be called to manually refetch the data.

Conclusion

I hope that this tutorial has helped you understand how to build a CRUD app with Next.js, React Query, React Hook Form, and Yup. These tools are powerful and can help you create user-friendly, high-performance apps with minimal effort.

Remember to use Next.js to build server-rendered React apps, React Query to fetch and cache asynchronous data, React Hook Form to manage forms, and Yup to validate form data. With these tools in your toolbelt, you should have everything you need to build a CRUD app that meets the needs of your users.

If you have any questions or need further assistance, don't hesitate to ask!

...



📌 Building a CRUD App with Next.js, React Query, React Hook Form, and Yup


📈 112.5 Punkte

📌 React 19, handling forms using useOptimistic and useFormStatus along with React Hook Form and Zod … practical example


📈 43.1 Punkte

📌 Creating Dynamic Forms with React, Typescript, React Hook Form and Zod


📈 41.31 Punkte

📌 Crafting Forms in React: Vanilla vs. React Hook Form vs. Formik


📈 39.53 Punkte

📌 React Hook Form's Ritual: Elegant Forms in React


📈 39.53 Punkte

📌 This Week In React #146: Concurrency, Server Components, Next.js, React-Query, Remix, Expo Router, Skia, React-Native...


📈 38.82 Punkte

📌 What is react-query? Why should we use react-query?


📈 36.77 Punkte

📌 Criei um hook personalizado para buscar dados da API do Rick and Morty com React Query


📈 36.07 Punkte

📌 rConfig up to 3.9.4 lib/crud/search.crud.php Command privilege escalation


📈 35.76 Punkte

📌 How to Validate Forms with Zod and React-Hook-Form


📈 34.25 Punkte

📌 CodeSOD: Query Query Query


📈 33.97 Punkte

📌 Difference between Action Hook and Filter Hook in WordPress


📈 33.58 Punkte

📌 React forms: Formik and Yup intro


📈 33.51 Punkte

📌 Converting React Forms to Formik and Yup


📈 33.51 Punkte

📌 This Week In React #127: Nextra, React-Query, React Documentary, Storybook, Remix, Tamagui, Solito, TC39, Rome...


📈 32.51 Punkte

📌 This Week In React #131: useReducer, Controlled Inputs, Async React, DevTools, React-Query, Storybook, Remix, RN , Expo...


📈 32.51 Punkte

📌 Simple React-Hook-Form v7 Tutorial with Typescript


📈 32.47 Punkte

📌 Formularios dinámicos con React Hook Form. 📝


📈 32.47 Punkte

📌 Dynamic forms with React Hook Form. 📝


📈 32.47 Punkte

📌 Epic Next JS 14 Tutorial Part 7: Next.js and Strapi CRUD Permissions


📈 32.29 Punkte

📌 Demystifying React Memoization: Understanding React.memo() and the useMemo hook


📈 31.81 Punkte

📌 👨🏼‍💻 Building a news app with React Native, Expo Router, and Tanstack Query 📰


📈 31.17 Punkte

📌 The SQL to CRUD: The Use of Structured Query Language to Create, Read, Update, and Destroy


📈 30.98 Punkte

📌 Wow! Server Actions are now Stable from Next.js 14! Dramatic changes in React and Next's form


📈 30.98 Punkte

📌 Fix the "React Hook is Called Conditionally" Error in React


📈 30.03 Punkte

📌 How to Build a Basic CRUD App with NextJS, TS, React, Redux-Tookit and MUI5 Components


📈 29.78 Punkte

📌 Build a Task Manager CRUD App with React and Hygraph


📈 29.78 Punkte

📌 Cgiscript.net csMailto csMailto.cgi form-to/form-from/form-results privilege escalation


📈 28.52 Punkte

📌 It's Black Hat and DEF CON in Vegas this week. And yup, you know what that means. Hotel room searches for guns


📈 28.23 Punkte

📌 We checked and yup, it's no longer 2001. And yet you can pwn a Windows box via Notepad.exe


📈 28.23 Punkte

📌 Dive into Backend Development by Building a CRUD API with Node and MongoDB


📈 27.61 Punkte

📌 Creating a CRUD Application with React: Mastering useState and useEffect


📈 26.72 Punkte

📌 Someone checked and, yup, you can still hijack Gmail, Bitcoin wallets etc via dirty SS7 tricks


📈 26.45 Punkte











matomo