3

I'm trying to fetch some data inside a React hook. Nothing fancy here, just some loading text and then replace once my data loads.

But I keep hitting my catch block and get Failed to fetch data: Cannot read property 'get' of undefined TypeError: Cannot read property 'get' of undefined printed to the console.

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

const DataPanel = () => {
  let [isLoading, setLoading] = useState(false);
  let [data, setData] = useState();

  useEffect(() => {
    async function getData() {
      let response;
      setLoading(true);
      try {
        response = await axios.get("urltosomewhere");
        setData(response);
      } catch (e) {
        console.log(`Failed to fetch data: ${e.message}`, e);
        return;
      } finally {
        setLoading(false);
      }
    }

    getData();
  });

  return (
    <div>
      <div>{isLoading ? <span>Loading...</span> : <span>{data}</span>} </div>
    </div>
  );
};

export default DataPanel;
Devon Deason
  • 125
  • 2
  • 8

1 Answers1

10

You need to import axios from 'axios', not import { axios } from 'axios'.

This is because the axios module default exports the axios class. It's not a named export so it can't be imported using the method you tried.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143