I have a custom hook named useFetchMyApi wrapping a fetch call to API endpoint. The function hook accepts a parameter and it is included in the post body. The data array output is dependent on the hook parameter.
On the UI, the App component calls useFetchMyApi once. A button click handler will call subsequent useFetchMyApi to update a list on the UI.
My issues:
- I can't call
useFetchMyApiin the event handler because it violates the rules of hook. - How do I refresh the list of items dependent on the response of
useFetchMyApi?
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
const useFetchMyApi = (location = "") => {
const [items, setItems] = useState([]);
useEffect(() => {
// let's stimulate the API call with a 2 seconds response time
setTimeout(() => setItems([location, Math.random()]), 5000);
}, [location]);
return { items };
};
export default function App() {
const locationSelect = useRef(null);
const { items } = useFetchMyApi("mylocation1");
const onButtonClicked = (event) => {
const selectedLocation = locationSelect.current.value;
// Call api and refresh items by location
// Fix here??
//useFetchMyApi(selectedLocation);
};
return (
<div className="App">
<select ref={locationSelect}>
<option value="location1">Location 1</option>
<option value="location2">Location 2</option>
</select>
<button onClick={onButtonClicked}>Refresh</button>
<ul>
{items.map((item) => (
<li>{item}</li>
))}
</ul>
</div>
);
}
https://codesandbox.io/s/stupefied-water-1o6mz?file=/src/App.js:0-1055