I am building a frontend application with react
i want to store the value of phone on useState but i am not getting the expected result
The last character typed does not show
I have used callback to display the same result
import React, { useState } from 'react'
export const terr = () => {
const [selectedData, setSelectedData] = useState({})
const handleChange = (value) => {
console.log(`selected ${value}`);
setSelectedData(selectedData => ({
...selectedData,
[e.target.name]: e.target.value
}));
console.log(`selected data `, selectedData);
};
return (
<div>
<input name="phone" value={selectedData} onChange={handleChange} />
</div>
)
}
2
Answers
I think this is what you wanted to achieve
Note that the
console.log
inside thehandleChange
function always shows an "old"selectedData
value becausesetSelectedData
is async, try logging it withuseEffect
or directly inside the JSX to confirmWhat seems to be wrong with your code is two things:
value
property on theinput
is not neededhandleChange
function should take a parameter ofevent
(see HTMLElement: change event)sandboxed demo of the above in action
https://stackblitz.com/edit/stackblitz-starters-yhksn3?file=src%2FApp.tsx
video demo of the above in action
https://www.loom.com/share/4751379be5c04f10adcb61e241551b90