skip to Main Content

I am trying to get api call on click, but I’m stuck with my console just showing null. I want on different items clicks, different api categories would be called.

 const [category, setCategory] = useState("");
  useEffect(() => {
    axios
      .get(`${url}${category}`)
      .then(function (response: any) {
        console.log(response.data.meals);
      })
      .catch(function (error: any) {
        console.log(error);
      });
  }, [category]);

  const onClickHandler = (e: any) => {
    setCategory(e.target.value);
  };
<li value="Seafood" onClick={onClickHandler}>
     Seafood
</li>

I was expecting like filter buttons to click, and then items would show up based on the filter you click.

2

Answers


  1. I don’t know much but maybe it can work like this, I apologize if it is wrong.

    const [category, setCategory] = useState('');
    
      useEffect(() => {
        if (category) {
          axios
            .get(`{url}${category}`)
            .then(function (response) {
              console.log(response.data.meals);
            })
            .catch(function (error) {
              console.log(error);
            });
        }
      }, [category]);
    
      const onClickHandler = (e) => {
        setCategory(e.target.getAttribute('value'));
      };
    
      return (
        <ul>
          <li value="Seafood" onClick={onClickHandler}>
            Seafood
          </li>
          {/* Add more li elements with different categories and onClickHandler */}
        </ul>
      );
    }
    
    Login or Signup to reply.
  2. The value property of a li element is reserved, and it tells the order of the li in its parent ol, as you can read on mdn:

    This integer attribute indicates the current ordinal value of the list item as defined by the <ol> element. The only allowed value for this attribute is a number…

    You would wanna use a button, which will work with your attempt and is made for handling clicks. You could nest it in your li. But if, for some reason, you want only the li, I would suggest a data attribute to avoid confusion:

    const onClickHandler = (e: any) => {
      setCategory(e.target.getAttribute("data-value"));
    };
    
    <li data-value="Seafood" onClick={onClickHandler}>
        Seafood
    </li>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search