0

I use useState like this and onclick event with name genreHandler:

    const [clickedGenre, setClickedGenre] = useState<string>(null)

    const genreHandler= (event: React.MouseEvent<HTMLLIElement>) => {
      console.log(clickedGenre)
      const li: HTMLLIElement = event.currentTarget;
      setClickedGenre(li.id);    
      axios.get(API_URL+"products?category.genre="+clickedGenre)
        .then((response) => {
          setProductList( response.data );
        })
        .catch((error)=>{
          console.log(error)
        }),[clickedGenre]
      }

here's my li tag

    <li className="list-group-item text-uppercase" 
      key= {category.id} id={category.genre} 
      onClick={genreHandler}>{category.genre}</li>

When I click on li the usestate (clickedGenre) still null not change to {category.genre}. It's change on double click. Please help me, what's wrong with my code

some-user
  • 3,888
  • 5
  • 19
  • 43
Graciela
  • 28
  • 5

1 Answers1

3

The problem is this part of your code

  setClickedGenre(li.id);    
  axios.get(API_URL+"products?category.genre="+clickedGenre)

React is asynchronous, so clickedGenre will not have the updated value yet when used at axios, so that's why it is OK the second time (after the asynchronous update).

So the correct code would be to use directly the li.id value

  setClickedGenre(li.id);    
  axios.get(API_URL+"products?category.genre=" + li.id)
Apostolos
  • 10,033
  • 5
  • 24
  • 39