I am attempting to set the time (mm:ss) by taking separate inputs for mins and secs with one use of useState
and combining them with another for keeping track of the overall form data, however I cannot seem to get the combined string to push into the form data...
I think I may be setting the data incorrectly somehow...
const Modal = ({show, handleClose, handleAdd, children}) => {
const today = new Date().toISOString().substr(0, 10);
let initialFormState = {
date: today,
distance: '5.23',
time: ''
};
let initialTimeState = {
mins: 0,
secs: 0
};
const [formData, setFormData] = useState(initialFormState);
const [timeData, setTimeData] = useState(initialTimeState);
const submitData = event => {
event.preventDefault();
console.log({timeData});
// Add correctly formatted time to main formData
const {mins, secs} = timeData;
const time = `${mins}:${secs}`;
setFormData({...formData, 'time': time});
console.log(formData); // Here I can see that the 'time' field is empty...
}
return (
...
);
};
export default Modal;
setFormData
changes are happening asynchronously, unfortunately you won't see the modification immediately. Instead you can use useEffect
hook to catch changes of your state.
Try as the following instead:
useEffect(() => {
console.log(formData);
}, [formData]);
Read further about useEffect
hook at Using the Effect Hook link.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.