Home > database >  React setState happens after second click
React setState happens after second click

Time:10-05

I am trying to set data in setSinglePostData() from another data source but its showing enter image description here

as you can see:

const [singlePostData, setSinglePostData] = useState([]);

<div>
{allPosts.map((post, index) => (
<h3
  style={{ marginLeft: 40, marginTop: -30 }}
  onClick={() => {
   setSinglePostData({
    ...post,
    index: index,
   });
   console.log(singlePostData);
   getPosts();
 }}
>
b\{post.user.name}
</h3>
))}
</div>

.map part

{singlePostData.map((post, index) => (
  <h2>{post.title}</h2>
))}

get all posts function

  const getPosts = async () => {
    const data = await getDocs(postsControllerRef);
    setPosts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    setLoading(false);
  };

CodePudding user response:

Objects, {} in JavaScript do not have the method .map(). It's only for Arrays, [].

So in order for your code to work change:

 onClick={() => {
   setSinglePostData({
    ...post,
    index: index,
   });
   console.log(singlePostData);
   getPosts();
 }}
>

to

 onClick={() => {
   setSinglePostData([
    ...post,
    index: index,
   ]);
   console.log(singlePostData);
   getPosts();
 }}
>

Because with your variant you are using ... spread operator inside Object {} and that change the state to Object instead of Array

  • Related