1

I have an array of objects

const data= [
    { id:1,name:"apple", city:"ban" },
    { id:2,name:"mango", city:"hyd" }
]

And I have two input fields when the user fills. if !null then I need to add an object to "data" {id:2,name:"apple",city:"nel"} and the id of the 2 in the data object should be 3 and if again the user makes it to null ie deleted the value from the input field need to remove this {id:2,name:"apple",city:"nel"} and make the id from 3 to 2. similarly of the user gives 2 inputs i need to add 2times {id:2,name:"apple",city:"nel"},{id:3,name:"apple",city:"nel"} and make the id of 2 to 4. similarly if the user deletes eaither/or deletes both or single data from the input i need to add or remove the data array accordingly can anyone please help me with this in react with hooks

1
  • i think i can use useEffect(()=>{},[input1,input2]) but i am not getting whats the condition to be used inside Commented Feb 21, 2021 at 18:36

1 Answer 1

2

You can track the form values with a single useState() hook.

You can use both input onChange event handlers, and form onSubmit event handler to build a component that behaves like you want.

The following is an example React component with hooks you can take as a starting point to manage your state. Please take it as a template and tweak it as needed to fulfill your actual requirement.

const storedData = [
  { id: 1, name: 'apple', city: 'ban' },
  { id: 2, name: 'mango', city: 'hyd' },
]
let nextId = 3

const MyFormComponent = () => {

  const initialFormData = { name: '', city: '' }
  const [formData, setFormData] = useState(initialFormData)

  const clearFormData = () => {
    setFormData(initialFormData)
  }

  const handleOnInputChange = (event) => {
    const { value, name } = event.target

    // merge previous formData with the new value from input
    setFormData({
      ...formData,
      [name]: value,
    })
  }

  const handleOnSubmit = (event) => {
    // prevent HTML form default handler (navigation, etc.)
    event.preventDefault()

    const { name, city } = formData
    // OPTIONAL: handle form data validations
    if (name === '') {
      // no "name" provided
      alert('Must specify a name!')
      return
    }
    // input1 "name" and input2 "city" are available in formData
    // TODO handle the form data and implement your application logic / update storedData / etc.
    // TODO a rough example below, please tweak it to match your requirements
    const existingEntryByIndex = storedData.findIndex(
      ({ name }) => formData.name === name
    )
    if (existingEntryByIndex >= 0 && formData.city === '') {
      // name exists and city value is empty => delete this entry
      // NOTE: city value can't be null, because it will be always a string. Maybe, you can use "null" string though.
      storedData.splice(existingEntryByIndex, 1)
    } else {
      // name exists and city not empty, or name is new => add a new city
      storedData.push({ id: nextId, name, city })
      nextId++
    }
    // --- end of rough example ---

    // OPTIONAL: clear the form values ->
    clearFormData()
  }

  return (
    <div className={'my-form-container'}>
      <form onSubmit={handleOnSubmit}>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleOnInputChange}
        />
        <input
          type="text"
          name="city"
          value={formData.city}
          onChange={handleOnInputChange}
        />
      </form>
    </div>
  )

For further reference, you can check the React docs to learn about more techniques and ways to handle form inputs, and events.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.