I recently asked a Stack Overflow post about useState()
taking 2 clicks. I was told I could immediately update a boolean state by doing setState(state => !state)
. However, this only works for booleans. Take this example:
let [popularQuotes, setPopularQuotes] = useState([])
let [newQuotes, setNewQuotes] = useState([])
let [selected, select] = useState("popular")
const getQuotes = async() => {
Post('https://example.com/api/quotes', {
sort: selected
}).then((r) => selected == "popular" ? setPopularQuotes(r) : setNewQuotes(r))
}
When I want to toggle from popular quotes to new quotes, such as like this onClick={() => {select("popular"); getQuotes()}}
, it takes 2 clicks, as the state newQuotes
remains initially unchanged for the first click (just being an empty array). How can I counteract this and update the state on the first click?