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

How do I set the type of 'user' properly in useState [user, setuser], so that I dont get type error when I extract the json data in the return? React

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.

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

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.

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