I am trying to update 1 quote inside of an array of “quotes”
const [quotes, setQuotes] = useState([]);
const [quoteToUpdate, setQuoteToUpdate] = useState(initialValues);
When I click on a switch (checkbox) I set quoteToUpdate with the quoteToUpdate
with the selected quote data, and update the switch from true to false or vice versa.
const onCheckboxChange = async (e, selectedQuote) => {
setQuoteToUpdate({...selectedQuote, [e.target.name]: e.target.checked});
};
The Problem I’m having is, right after I update the quoteUpdate
, I need to send the updated object to the backend to update. But since React state is sync
, the quoteToUpdate
does not get updated instantly but instead queues up.
What I’ve tried:
I’ve tried putting the onSubmit()
function inside a useEffect
but it’s clearly not working.
useEffect(() => {
onSubmit(quoteToUpdate);
}, [quoteToUpdate])
onSubmit looks like this:
const onSubmit = (quoteToUpdate) => {
axiosWithAuth().put('/quotes/' + quoteToUpdate.id, quoteToUpdate)
.then((res) => {
const updatedQuote = res.data;
setQuotes(quotes.map(quote => (
quote.id === updatedQuote.id ? {...quote, 'is_complete': updatedQuote.is_complete} : quote
))
);
const alertContent = `quote updated successfully.`;
halfmoon.stickyAlerts = document.getElementsByClassName("sticky-alerts")[0]
halfmoon.initStickyAlert({
content: alertContent, alertType: "alert-success", title: "Successfully updated"
})
}).catch(error => {
console.log(error.message);
});
}