I have come across this from numerous angles, and currently my code looks like this, and I get the following error:
Property 'albums' does not exist on type 'never'
I am using React hooks, but getting an error from the data
object updated with useState
. data
has an property albums
that I am not sure how to define, or where to do this.
import React, { useState } from 'react';
interface ArtistProps {
artistName: string,
}
const Artist: React.SFC< ArtistProps > = ({ artistName }) => {
const [data, setData] = useState(null);
return (
<>
<p>{artistName)}</p> // this is fine
<p>{data.albums}</p> // error here
</>
);
}
Try this:
const [data, setData] = useState<null | {albums: any}>(null);
Then use the data
variable like
data!.albums
The !
is to let typescript know that you're sure the value is not null
. But even better is to explicitely check the value for null
e.g. data ? data.albums : 'no data'
P.S. Instead of {albums: any}
add your appropriate inerface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With