score:0

Accepted answer
const useFetch = (url:string) => {
  const [loading, setLoading] = useState(false);
  const [quote, setQuote] = useState('');

  const refetch = useCallback(() => {
    setLoading(true);
    fetch(url)
      .then((x) => x.text())
      .then((y) => {
        //setQuote(y);
        setQuote(String(Math.random()));
        setLoading(false);
      });
  }, [url]);

  return { quote, refetch, loading };
};

const App = () => {
  const { quote, refetch, loading } = useFetch('/api/rand');

  useEffect(() => {
    refetch();
  }, []);

  return (
    <div>
      <h1>Quotes</h1>
      <button onClick={refetch}>Get Quote</button>
      {loading ? ' loading...' : ''}
      <div>{quote}</div>
    </div>
  );
};

score:0

const useFetch = (url: string) => {
  const [state, setState] = useState<Payload>({data: null, loading: true})
  const [reloadFlag, setReloadFlag] = useState(0)

  useEffect(() => {
    if(reloadFlag !== 0){ // remove this if you want the hook to fetch data initially, not just after reload has been clicked
      setState(state => ({ data: state.data, loading: true }));
      fetch(url)
        .then(x => x.text())
        .then(y => {
          setState({ data: y, loading: false });
        });
    }
  }, [url, setState, reloadFlag])

  return [state, ()=>setReloadFlag((curFlag)=>curFlag + 1)];
  }

const App = () => {

  const [data, reload] = useFetch(
    "/api/rand"
  );

  return (
    <div>
      <h1>Quotes</h1>
      <button onClick={reload}>Get Quote</button>
      <div>{quote.data}</div>
    </div>
  )
}

score:0

const useFetch = (url: string) => {
  const [state, setState] = useState<Payload>({data: null, loading: true})

  setState(state => ({ data: state.data, loading: true }));
    fetch(url)
      .then(x => x.text())
      .then(y => {
        setState({ data: y, loading: false });
      });

  return state;
  }

export default useFetch;

score:2

import React, { useState, useEffect, useCallback } from "react";

const App = () => {
  const [quote, setQuote] = useState<Payload>({data: null, loading: true})

  const handleGetQuote = useCallback(() => {
    setQuote(state => ({ data: state.data, loading: true }));
    fetch("/api/rand")
      .then(x => x.text())
      .then(y => {
        setQuote({ data: y, loading: false });
      });
  }, []);

  useEffect(() => {
    handleGetQuote();
  }, [handleGetQuote]);

  return (
    <div>
      <h1>Quotes</h1>
      <button onClick={handleGetQuote}>Get Quote</button>
      <div>{quote.data}</div>
    </div>
  )
}

export default App;

Related Query

More Query from same tag