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

How can I make API calls on click with different categories in React using axios?

i am trying to get api call on click, but im stuck and with this in console just shows null,
I want that on different item clicked different api category 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

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 :

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>
  );
}
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