score:2

Accepted answer

Your hook can provide a function to fetch/refetch the data:

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(false);

  const fetchData = async (resortId) => {
    setIsLoading(true);

    try {
      const res = await fetch(url, {id: resortId});
      const json = await res.json();
      setResponse(json);
      setIsLoading(false);
    } catch (error) {
      setError(error);
      setIsLoading(false);
    }
  }

  return [
    response, 
    error, 
    isLoading,
    fetchData
  ];
};

You can then call fetchData whenever you want to update your search:

const App = () => {
  const [resort, resortIsLoading, resortError, fetchResort] = useFetch(config.API_URL_GET_RESORT);


 const handleChangeResort = (event) => {
    const id = event.target.value;
    fetchResort(id);
 };

  return (
    <>
      <Select
        labelId="resort-label"
        id="resort"
        label="resort"
        value={resort ? resort.id : ""}
        onChange={handleChangeResort}
      >
        {resorts.length ? (
          resorts.map(c => (
            <MenuItem key={c.id} value={c.id}>
              {c.name}
            </MenuItem>
          ))
        ) : (
          <MenuItem key={0} value={""}>
            <em>loading resorts list...</em>
          </MenuItem>
        )}
      </Select>
    </>
  )}
}

score:1

I would do something like so:

const useFetch = (url) => {
  const [state, setState] = React.useState([null, false, null]);

  const fetchData = async (options) => {
    setState([null, true, null]);

    try {
      const res = await fetch(url, options);
      const json = await res.json();
      setState([json, false, null]);
    } catch (error) {
      setState([null, false, error]);
    }
  }

  return [
    ...state, // response, loading, error
    fetchData
  ];
};

And then, you could use:

const [resorts, resortsIsLoading, resortsError, fetchResorts] = useFetch(config.API_URL_GET_RESORTS);
const [resort, resortIsLoading, resortError, fetchResort] = useFetch(config.API_URL_GET_RESORT);

useEffect(() => {
  fetchResorts()
}, [])

Related Query

More Query from same tag