Reputation: 311
I have an object and a note field as states in the React component. When users enter a note I change the note state and add it to my object. But I am getting the wrong input in my object.
If I enter "hello" in the note field, "hell" get added to the object and the object becomes {note: "hell"}
const SelectedSymptom = () => {
const [note, setNote] = useState("");
useEffect(() => {
const update = async () => {
await setSelectedSymptom((prev) => {
return {
...prev,
feature: feature,
since: since,
severity: severity,
place: place,
colour: colour,
note: note,
};
});
};
update();
console.log(selected);
}, [since, feature, severity, place, colour, note]);
return (<div>
<label for="Note">Note</label>
<textarea
style={{ border: "1px solid", borderRadius: "5px", padding: "5px" }}
id="Note"
name="Note"
rows="3"
cols="auto"
value={note}
placeholder="Enter note here"
onChange={(e) => setNote(e.target.value)}
></textarea> </div>
);
};
Upvotes: 0
Views: 497
Reputation: 13588
Your update is an async function (so I assume you have async operations in there, more than just setSelectedSymptom );
if you put console.log(selected) after update(), you are just logging previous value, because the console.log is executed before update() is finished.
Just move console.log(select) to outside useEffect.
useEffect(() => {
const update = async () => {
await setSelectedSymptom((prev) => {
return {
...prev,
feature: feature,
since: since,
severity: severity,
place: place,
colour: colour,
note: note,
};
});
};
update();
}, [since, feature, severity, place, colour, note]);
console.log(selected);
Upvotes: 2