skip to Main Content

I have a react form where I have to put in a logic if startdate > endate, it should revert the startdate to current date. I am adding the form values in an useState array object.
Initial array object looks like this –

num:"12345"
startdate: "06/14/2023"
enddate: "06/01/2023"

I have put in a validation check and once it finds that startdate > enddate, it should change the value of startdate to current date.

const [form, setForm] = useState({})

  const revertStartDate = (field) => {
    if (field == 'enddate') {
      setForm((prev) => {
        prev.startdate = new Date().toISOString() // using internal day calculator
        return {...prev}
      }
      )
    }
  }

The above code changes the form to below :

num:"12345"
startdate: "04/19/2023"
enddate: "06/01/2023"

But it doesn’t reflect the same on the UI. The UI still shows 06/14/2023 for the startdate. I have read other answers that it’s not changing the state even though the values are getting changed.

Any suggestion on how to re-render the form for the startdate?

2

Answers


  1. I can’t comment due to low contribution but it would be helpful if you also provide code snippet to your <input>.

    You might want to consider reading the docs:
    Controlling an input with a state variable

    A controlled input makes sense if you needed state anyway—for example,
    to re-render your UI on every edit.

    Login or Signup to reply.
  2. I think you can’t mutate state directly. If you want to make sure read this doc.

        const [form, setForm] = useState({})
    
      const revertStartDate = (field) => {
        if (field == 'enddate') {
          setForm((prev) => {
            return {
              ...prev,
              startdate: new Date().toISOString()
            }
          }
          )
        }
      }
    

    In my opinion updating state like that doesn’t trigger re-render.

         setForm((prev) => {
           prev.startdate = new Date().toISOString() // using internal day calculator
           return {...prev}
         }
    

    Do you want update this directly? Use immer!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search