0

I'm trying to retrieve some data from a json to use later in a chart.

My issue is that using useState, it gets me a never type data, so I can't access fields.

const [myData, setData] = useState([]);

const url = 'url';

axios.get(url)
      .then(res => {
        setData(res.data);

        myData.forEach( e=> {
          console.log(e.name);
        })
      }).catch(function (error) {
        // handle error
      })

When i print the console.log the name results as an error because Property 'name' does not exist on type 'never'.

How could I fix this?

EDIT: I'm using Typescript

1 Answers1

0

You should declare the type of useState to be any so that while accessing certain fields within it which can be undefined/null which misleads the compiler into thinking that myData array values won't be anything but undefined. You can explicitly define a type to avoid this

const [myData, setData] = useState<any[]>([]);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400