Check if input has the same value React

Viewed 545

Question:

How to prevent submit if value hasn't changed?
I tried to do this using useState.

Snippet:

import React from 'react'
import {Formik, Form, Field} from 'formik'

const Search = () => {

  const [searchValue, setSearchValue] = useState('')

  const handleSubmit = q => {
    window.location.href = `https://for-example.com/search?q=${q}`
  }

  return (
    <Formik onSubmit={({q}, {setSubmitting}) => {
      setSubmitting(false)
      setSearchValue(q) // <===
      return q !== searchValue && handleSubmit(q) // <===
    }} initialValues={{q: ''}} render={() => (
      <Form>
        <Field name='q' />
      </Form>
    )}/>
  )
}

P.S. This works but I think it's not worth creating useState for this simple task. Can I check the search value in another way?

1 Answers

If you're changing window location in your handleSubmit function, you don't need to worry about future states. You can use dirty prop passed in render prop, something like this:

import React from 'react'
import {Formik, Form, Field} from 'formik'

const Search = () => {

  const handleSubmit = q => {
    window.location.href = `https://for-example.com/search?q=${q}`
  }

  return (
    <Formik onSubmit={({q}, {setSubmitting}) => {
      setSubmitting(false)
      handleSubmit(q)
    }} initialValues={{q: ''}} render={({ dirty, handleSubmit, isSubmitting }) => (
      <form onSubmit={handleSubmit}>
        <Field name='q' />
        <button type="submit" disabled={!dirty || isSubmitting}>
          Submit
        </button>
      </form>
    )}/>
  )
}

If you're not changing location on submit, or for any other reason same form can be submitted multiple times (with different values), than you need state in some form, either local like you did here, or global.

Hope it helps.

Related