use-http icon indicating copy to clipboard operation
use-http copied to clipboard

Data not populated at mount

Open maximelebastard opened this issue 2 years ago • 5 comments

Describe the bug When using the provided example, no data is populated into the state.

To Reproduce Use that example

import { useFetch } from "use-http";

function Data() {
  const {
    loading,
    error,
    data = [],
  } = useFetch(
    "https://myserver.com/?query=toto",
    {},
    []
  );

  return (
    <>
      {JSON.stringify(data, error, loading)}
    </>
  );
}

export default Data;

Expected behavior The data appears into the data attribute

Actual behavior The request is executed and visible into the Network tab of the Chrome Dev Tools, but no data is put in the state.

maximelebastard avatar May 16 '22 23:05 maximelebastard

+1

@maximelebastard Did you figure out anything?

MuzafferDede avatar May 17 '22 06:05 MuzafferDede

@MuzafferDede Nope sorry, I ended up switching to axios-hooks https://www.npmjs.com/package/axios-hooks

maximelebastard avatar May 20 '22 09:05 maximelebastard

@maximelebastard I figured out, It is because of React 18's strict mode. If you turn off, it will be fine or you can rollback to React 17 until this is handled by use-http package. Some other packages also faced this.

MuzafferDede avatar May 20 '22 10:05 MuzafferDede

It is happening due to abort on unmount feature useEffect(() => request.abort, []) at https://github.com/ava/use-http/blob/031b2ee8e00241fc8585dda7cf0c135eda5a181a/src/useFetch.ts#L243

If I remove this line it is working, but it is making duplicate get requests as component mounts, unmounts and remounts again in React 18 StrictMode.

Now I'm trying to solve this problem with abort the requests on unmount and making it work in React StrictMode.

Please let me know if you have any inputs

@alex-cory

krishnasaga avatar Dec 03 '22 18:12 krishnasaga

I suppose this is the same issue that I see here.

An extract from my functional component:

    const [date, setDate] = useState(formatDate(nextDate(0), 'yyyy-MM-dd'))  // next Sunday
    const [jsonData, setJsonData] = useState({});

    // initializing Http API for fetching data from database
    const {loading, error, data} = useFetch(
        `https://${window.location.hostname}${proxy}/query?date=${date}`, 
        {responseType: 'json'}, 
        [date]
    );
    useEffect(() => {
        if (data) {
            setJsonData(data)
        }
    }, [data])

So I want to execute the effect when data becomes available. UseFetch is run when the component mounts, I can see the response coming back in the console, but the effect is not running. When I do setDate(), useFetch runs again on the new url, and then the effect is executed correctly!

Best regards, Vic

vicmortelmans avatar Mar 26 '23 13:03 vicmortelmans