Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the proper way to set state with React Hooks?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading