I have a Posts component with posts array, including few posts just for example. Now I'm trying to add new post to my array and I want that post to be rendered with others. I dont have much experience with React, so I dont know how to add new element to an array. I tried to do it with "setPosts(...posts, newPost)", but it dont work, now all my posts disappeared after render.
const Posts = () => {
const [posts, setPosts] = useState([
{id: 1, title: 'First Post', content: 'First Post Content'},
{id: 2, title: 'Second Post', content: 'Second Post Content'},
{id: 3, title: 'Third Post', content: 'Third Post Content'}
]);
const [newId, setNewId] = useState('');
const [newTitle, setNewTitle] = useState('');
const [newContent, setNewContent] = useState('');
const handleIdChange = (e) => {
setNewId(e.target.value)
}
const handleTitleChange = (e) => {
setNewTitle(e.target.value)
}
const handleContentChange = (e) => {
setNewContent(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault();
const newPost = {
id: newId,
title: newTitle,
content: newContent
}
setPosts(...posts, newPost)
}
return <div>
<form onSubmit={handleSubmit} className='posts-form'>
<label>
New ID: <input type='text' onChange={handleIdChange} value={newId} />
</label>
<br />
<br />
<label>
New Title: <input type='text' onChange={handleTitleChange} value={newTitle} />
</label>
<br />
<br />
<label>
New Content: <input type='text' onChange={handleContentChange} value={newContent} />
</label>
<br />
<br />
<input type='submit' value='Add' />
</form>
<PostsList posts={posts} />
</div>
}
const PostsList = (props) => {
return <div className='posts-list'>
{ props.posts.length > 0 ? props.posts.map(
(post) => <div key={post.id} className='post'>
<h1 className='post-title'>{post.id}. {post.title}</h1>
<p className='post-content'>{post.content}</p>
</div>
) : <h1 style={{color: 'gray', fontFamily: 'monospace'}}>No posts found!</h1> }
</div>
}
I just want new post to be rendered with other posts, but it showing "No Posts found!" after submitting.
CodePudding user response:
You're almost right, you just forgot the array brackets:
setPosts([...posts, newPost])
CodePudding user response:
Use brackets in your state like this and use spread operator on the posts state it will append the previous posts
setPosts([...posts, newPost])
CodePudding user response:
In your implementation you're doing:
setPosts(...posts, newPost)
doing so, you're passing 2 arguments to the setPosts
function.
Whereas, setPosts
functions expect you to pass a single argument representing your updated state which is the new array.
You can create a new array using spread operator ...
like this:
[...posts, newPost]
The above statement spreads all the values from posts
array, and add a new element newPost
at the end of the new array created using []
.
So your implementation should be like this:
setPosts([...posts, newPost])
Hope that helps!