Cannot read properties of null (reading 'useState')

Viewed 59

im trying to create a custom hook to perform api requests, but im getting this error:

TypeError: Cannot read properties of null (reading 'useState')

Here´s the code

import { useEffect, useState } from 'react';

export const useFetch = (path) => {
  const [data, setData] = useState();

  const fetchData = async () => {
    try {
      const response = await fetch(`http://localhost:3000/api/${path}`);
      const { data } = await response.json();
      setData(data);
    } catch (error) {
      console.log(error);
    }
  };

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

  return {
    data,
  };
};

Next version

"next": "12.2.5"
"react": "18.2.0",
"react-dom": "18.2.0",
1 Answers

Because you setState clear you should write:

const [data, setData] = useState<Type(type of data)>();

Related