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?
>Solution :
Add an effect hook like this to your function component body for triggering the Api whenever selected is changed:
useEffect(() => {
getQuotes(selected);
},[selected]);
Change getQuotes to get selected value as a parameter:
const getQuotes = async(selectedItem) => {
Post('https://example.com/api/quotes', {
sort: selectedItem
}).then((r) => selectedItem == "popular" ? setPopularQuotes(r) : setNewQuotes(r))
}
Finally modify onClick callback like this:
onClick={() => select("popular")}