Issue
I am practicing typescript with react and fetching some data from an API I created a few days ago, API is working fine, am getting data for my front-end while fetching but when I try to use forEach or map method on that array of data it is throwing me an error:
Object is possibly 'undefined'
interface Posts {
_id: string
title: string
date: string
text: string
author_name: string
published: boolean
__v: number
}
const TextField = () => {
const [posts, setPosts] = useState<Posts>()
const fetchData = async () => {
const result = await fetch("https://ed-blog-api.herokuapp.com/api/posts")
const data = await result.json()
const posts = data.posts
setPosts(posts)
}
return (
<div>
<button onClick={fetchData}>Click</button>
{posts.forEach((post: object) => { // getting error here for posts
console.log(post)
})}
</div>
)
}
Solution
I think your Posts interface is actually the interface of a single Post
so:
interface Post {
_id: string
title: string
date: string
text: string
author_name: string
published: boolean
__v: number
}
type Posts=Post[]
Now in here, you don't need to type post as object anymore. Typescript will infer it itself.
const TextField = () => {
const [posts, setPosts] = useState<Posts|[]>([])
const fetchData = async () => {
const result = await fetch("https://ed-blog-api.herokuapp.com/api/posts")
const data = await result.json()
const posts = data.posts
setPosts(posts)
}
return (
<div>
<button onClick={fetchData}>Click</button>
{posts.forEach((post) => {
console.log(post)
})}
</div>
)
}
But actually the reason of that error, is that in JavaScript the type of null is also object! so if you type anything as object, you are saying it could be an array, object or null. if it is null, you can't use any properties of it.
Answered By - Erfan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.