This is a beginner question so please don’t hate. Please explain as much as you can.
The program is working just fine, but in the typescript console, I am getting this error.
Property 'bio' does not exist on type 'any[]'.
'use client';
import { useEffect, useState } from "react";
export default function Github(){
const [user , setUser] = useState([]);
let fetchUserData = () => {
fetch("https://api.github.com/users/userName")
.then(response => {
return response.json()
})
.then(data => {
setUser(data)
})
}
useEffect( () => {
fetchUserData()
}, [])
return (
<div>
{typeof(user.bio)}
</div>
)
}
This has happened when I am trying to extract the property from user. If I use alternative notation to grab the data, i.e, user['bio'], typescript does not show any error.
I am trying to understand React, Next JS and Typescript. I tried documentation and other tutorials.
I also tried to declare an interface above useState for user, but nothing worked. Please advice !
>Solution :
The easiest way is to provide a generic type parameter when calling useState():
// Declared somewhere, likely another file
interface User {
bio: string
}
const [user, setUser] = useState<User>();
This will result in the value being User | undefined, so you’ll still need to check the value isn’t null (or use null propagation):
<div>
{user?.bio}
</div>
Alternatively, you can provide a default value to useState():
// outside component
const BLANK_USER: User = { bio: '' }
// inside component
const [user, setUser] = useState(BLANK_USER)
Personally, I’d go with providing a type argument, as using a default value like this could get weird — it will be wrong if your type doesn’t specify all properties of a user, for example.
Note: in your example, you’ve passed an array ([]) as a default, which is wrong. You probably meant to pass an empty object {}, but TypeScript isn’t going to like that.