When i type input and on change editing.hours doesn't update input value but i see updated value in the console.
const nullableEntry = {
ID: '',
day: '',
hours: 0.0,
note: '',
};
const MonthTable = (props) => {
const [editing, setEditing] = useState(nullableEntry);
function handleHoursInput(e) {
editing.hours = e.target.value;
setEditing(editing);
}
return (
<input type="number" value={editing.hours} step="0.01" onChange={handleHoursInput} className="form-control" name="" />
);
};
export default MonthTable;
When i type input and on change editing.hours doesn't update input value but i see updated value in the console.
const nullableEntry = {
ID: '',
day: '',
hours: 0.0,
note: '',
};
const MonthTable = (props) => {
const [editing, setEditing] = useState(nullableEntry);
function handleHoursInput(e) {
editing.hours = e.target.value;
setEditing(editing);
}
return (
<input type="number" value={editing.hours} step="0.01" onChange={handleHoursInput} className="form-control" name="" />
);
};
export default MonthTable;
Share
Improve this question
asked Aug 24, 2019 at 7:02
ahmed waleedahmed waleed
5171 gold badge5 silver badges13 bronze badges
1
- 1 do not mutate state !!! – Code Maniac Commented Aug 24, 2019 at 7:09
3 Answers
Reset to default 15In React, you should avoid doing state-mutations, which means do not explicitly change something belonging to the existing state. In order for React to decide whether or not to re-render to reflect your changes, it needs to register a new-state.
Get in a good habit of creating a clone or deep-copy of the state, and then updating that.
Try something like this instead. In the below, we use the spread operator {...}
to clone the state before updating it:
const nullableEntry = {
ID: "",
day: "",
hours: 0.0,
note: ""
};
const MonthTable = props => {
const [editing, setEditing] = useState(nullableEntry);
function handleHoursInput(e) {
let newEdit = { ...editing };
newEdit.hours = e.target.value;
setEditing(newEdit);
}
return (
<input
type="number"
value={editing.hours}
step="0.01"
onChange={handleHoursInput}
className="form-control"
name=""
/>
);
};
Working sandbox: https://codesandbox.io/s/hopeful-bogdan-lzl76
Do not mutate state, editing.hours = e.target.value
mutates original state
change your handleHoursInput
function to something like this
function handleHoursInput(e) {
let hours = e.target.value;
setEditing({...editing, hours});
}
you can update state in functional components in this way
const [show, setShow] = useState(false)
const [scopesData, setScopesData] = useState(scopes)
const submitCallBack = (data) => {
setShowhowAlert(true)
setScopesData(...scopes, scopes.push({
id: generateKeyHash(),
title: data.data.scopetitle,
}))
}
these 3 lines of codes update the state correctly
[setScopesData(...scopes, scopes.push({
id: generateKeyHash(),
title: data.data.scopetitle,
}))