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>
)
}
const posts = data.postsand[posts, setPosts] = useState<Posts>()Just dosetPosts(data.posts ?? [])or something. To get "rid" of the possibly undefined issue you can doposts?.forEach((post) => console.log(post))Using the?operator the assertion will only be executed if posts is not undefined.Postand "Posts" isPost[], meaning it is an array of posts. So you could simply initialize your posts as[posts, setPosts] = useState<Post[]>([]). Then you could just useposts.map(post: Post => <div key={post._id}>Post works!</div>Using the "object" type is strongly discouraged, you should avoid doing that.