Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting a network error on page refresh? (get request)

I’m making a get request to an API in a useEffect(). When I navigate to the page from the homepage it loads fine, but as soon as i refresh the page http://localhost:3000/coins/coin I get a Unhandled Runtime Error: Error: Network Error.

export async function getServerSideProps({ query }) {
  const id = query;
  return {
    props: { data: id },
  };
}

function index({ data }) {
  const coinURL = data.id; // bitcoin
  const apiEndpoint = `https://api.coingecko.com/api/v3/coins/${coinURL}`;
  const [currentUser, setCurrentUser] = useState();
  const [coinData, setCoinData] = useState([]);

  useEffect(() => {
    const getData = async () => {
      const res = await axios.get(apiEndpoint);
      const { data } = res;
      setCoinData(data);
    };
    const getCurrentUser = async () => {
      const res = await axios.get(
        `http://localhost:5000/api/users/${session?.id}`
      );
      const { data } = res;
      setCurrentUser(data);
    };
    getData();
    getCurrentUser();

  }, [coinData, currentUser]);
}

Why does this happen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m recommending to do something like this:

const getData = async () => {
    try {
        const res = await axios.get(apiEndpoint);
        const { data } = res;
        setCoinData(data);
    } catch(err) {
        console.log(err)
    }
};

const getCurrentUser = async () => {
    try {
        const res = await axios.get(
            `http://localhost:5000/api/users/${session?.id}`
        );
        const { data } = res;
        setCurrentUser(data);
    } catch(err) {
        console.log(err)
    }
};

useEffect(() => {
    getData();
    getCurrentUser();
  }, [coinData, currentUser]);

if you do so, you will be able to view the exact error and fix it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading