Reputation: 21
I am doing a project that wants me to filter an API based on location. This filter is triggered by 5 buttons, all with different locations. To accomplish this, my plan was to create a storing part of the API's url, and concatenate it with the value of the button that was pressed. for example:
const url = 'https://www.my-example-api.com/api/json/filter.php?i=';
return axios.get(`${url}${selectedLocation}`)
I am able to call my API and display everything without a problem when I physically set selectedLocation. the only issue I'm running into is calling the value of the button that was pressed to the API file. I have a variable holding the value of the button that has been pressed, but I can't figure out how to send that to the api file.
here an example of how I have the location stored currently:
const [location, setLocation] = useState('');
const onClickhandler = (e) => {
setLocation(e.target.value);
};
return (
<button value="Canada" onClick={onClickHandler}>CANADA</button>
)
if anyone could point me in the right direction that would be amazing and thank you in advance.
Upvotes: 0
Views: 615
Reputation: 4410
You can achieve the result with useEffect
trigger when state changes
const [location, setLocation] = useState('');
useEffect(() => {
//Here do your api call
},[location])
const onClickhandler = (e) => {
setLocation(e.target.value);
};
return (
<button value="Canada" onClick={onClickHandler}>CANADA</button>
)
Upvotes: 1