I am trying to update the context through the "state" variable here a then render it in another component. The rendering works fine, but not the first time of submitting the form here, only the second time, third time etc. Any idea how to solve this? I tried to move dispatchDataState({ type: "ADD_DATA", payload: state })
into useEffect but then I cannot remove the entered value in the inputs after submitting it. Any idea?
import React, { useContext, useState, useEffect } from "react";
import DataContext from "../store/data-context";
function Form() {
const [name, setName] = useState("");
const [secName, setSecName] = useState("");
const [tel, setTel] = useState("");
const [note, setNote] = useState("");
const [state, setState] = useState({
name: "",
secName: "",
tel: "",
note: "",
});
const { dispatchDataState } = useContext(DataContext);
const handleSubmit = (e) => {
e.preventDefault();
console.log(name);
setState({
name: name,
secName: secName,
tel: tel,
note: note,
});
dispatchDataState({ type: "ADD_DATA", payload: state });
console.log(state);
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Jméno
<input
type="text"
required
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<label>
Příjmení
<input
type="text"
required
value={secName}
onChange={(e) => setSecName(e.target.value)}
/>
</label>
<label>
Telefonní číslo
<input
type="text"
required
value={tel}
onChange={(e) => setTel(e.target.value)}
/>
</label>
<label>
Poznámka
<input
type="text"
value={note}
onChange={(e) => setNote(e.target.value)}
/>
</label>
<input type="submit" value="Odeslat" />
</form>
</div>
);
}
export default Form;