I have a TypeScript question for you. I wonder how you 'specify' a single object in useState with the incoming properties of id, heading, text with an interface or such.
See code below:
import React, { useState, useEffect } from "react";
interface SinglePostProps {
match: any;
}
interface SinglePostState {
id: number;
heading: string;
text: string;
}
const Post: React.FC<SinglePostProps> = ({ match }) => {
useEffect(() => {
fetchSinglePost();
}, []);
const [singlePost, setSinglePost] = useState<SinglePostState>({});
const fetchSinglePost = async () => {
try {
const fetchSinglePost = await fetch(
`http://localhost:3001/api/posts/${match.params.id}`
);
const singlePost = await fetchSinglePost.json();
console.log("Single Post", singlePost);
setSinglePost(singlePost);
} catch (error) {
console.error(error);
}
};
return (
<>{/* <h1>{singlePost.heading}</h1>
<p>{singlePost.text}</p> */}</>
);
};
export default Post;
If I console log the object that is saved as singlePost state I get the following message:
As I understand it you want to specify if you're expecting an array for example or an object into the state. So when I did this is my PostList component which renders a list of objects inside of an array I did the following and it didn't complain:
const [items, setItems] = useState<PostListState[]>([]);
I'm quite new to TypeScript so it would be much appreciated if someone could explain how I can approach these kind of TypeScript error messages? :)
Thanks beforehand, Erik