DEV Community

Rajiv Chaulagain
Rajiv Chaulagain

Posted on

8 1 1 1 1

React Hook Form - Combined Add/Edit (Create/Update) Form Example

Today we are going to perform a crud app where we will add and edit the form with same component .
We will use react-router-dom , formik and yup. so let's dive to the code.

Create a component as AddEdit.js

import React, { useEffect, useState } from 'react'
import { Formik, Form } from 'formik'
import { useMutation, useQuery, useQueryClient } from 'react-query'


const AddEdit = () => {

  const history = useHistory()

  const user = useUser()

  const params: any = useParams()

  const queryClient = useQueryClient()

  const id: number = Number(params?.id)

  const isAddMode = !id

  const { data, isLoading, isError } = useQuery(['data', id], () => getData(id), {
    enabled: !!id,
  })

  const onFormSubmit = (values: any) => {
    isAddMode ? addFnc : editFnc
  }

  const initValues = {
    name: isAddMode ? '' : data?.name
  }

  return (
    <>
      <div className=''>
        <Formik validationSchema={Schema} initialValues= {initValues} onSubmit={onFormSubmit}>
          {(props) => (
            <Form className='w-100 pb-10'>
              <Field name="name" />
              <button
                type='submit'>
                  'Submit'
              </button>
            </Form>
          )}
        </Formik>
      </div>
    </>
  )
}

export default AddEdit
Enter fullscreen mode Exit fullscreen mode

So here , we created a function and hence we added the code.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video