I have an nested object in React functional component state, but I only can access first level of object if I use any
type.
export default function Detail() {
const [user, setUser] = useState<any>({});
const { id } = useParams();
useEffect(() => {
fetch('http://localhost:4000/users/' + id)
.then(response => {
return response.json();
})
.then(data => {
setUser(data);
})
}, []);
return (
<div>
<h1>Detail view</h1>
<p>ID: { user.id }</p>
<p>First name: { user.first_name }</p>
<p>Last name: { user.last_name }</p>
<p>Email: { user.email }</p>
<p>Gender: { user.gender }</p>
</div>
);
}
When trying to access user.company.name
it throws
Detail.tsx:40 Uncaught TypeError: Cannot read properties of undefined (reading 'name')
I made an interface for it, but it gives me an error if I'm trying to use it for state type.
interface UserInfo {
id: number;
first_name: string;
last_name: string;
email: string;
gender: string;
company: {
name: string;
department: string;
}
}
Argument of type '{}' is not assignable to parameter of type 'UserInfo | (() => UserInfo)'.
How can I use defined interface as state type?
{user.company.name}
}` to prevent the error. Not a typescript expert, but you probably need to assign an intial object that already has data for the interface properties. See also here: https://stackoverflow.com/questions/36745013/interface-states-and-props-in-typescript-react – Feb 13 '22 at 10:26