0

In functional component i am having onchange function where i am updating state but state is not updating immediately, means first if i enter first character it is reflecting when i enter second character, How can i update it immediately.

 const [customstartdate, setCustomstartdate] = useState();
  const [customenddate, setCustomenddate] = useState();
<Input
                      className={`form-control-digits not-empty`}
                      onChange={customHandler}
                      type="date"
                      id="meeting-time"
                      name="start_date"
                    />

const customHandler = (e) => {
    if (e.target.name === "start_date") {
      setCustomstartdate(e.target.value);
    }
    if (e.target.name === "end_date") {
      setCustomenddate(e.target.value);
    }
    //having some functionality here
  };
  • Setting state happens in batches, and the state variable will not be updated until a subsequent re-render. If you need the "new" value for subsequent code, keep it in a new variable. – crashmstr Aug 04 '22 at 12:43
  • @crashmstr can you provide an answer for that –  Aug 04 '22 at 12:48
  • Does this answer your question? [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – crashmstr Aug 04 '22 at 14:57

2 Answers2

1

You can use something like this

useEffect(() => {
    setName(name)
}, [name])
MNZ
  • 845
  • 7
  • 11
-1

Please search on google how to use react hooks,

when you use onChange he can't run your function directly, you need to write a callback that's run your function,

please follow my example and read more about react

const [name,setName] = useState("");
<div>
        <label>name</label>
        <input type="text" id="fname" onChange={(eve)=>setName(eve.target.value)}/>
</div>

following this example, you can see that I'm using a callback function to be able to use the useState

Elias Salom
  • 99
  • 1
  • 13
  • 1
    `onChange={customHandler}` is perfectly fine. It is a function and it gets called when a change triggers it (no difference from having an in-line function or arrow function). – crashmstr Aug 04 '22 at 14:59