Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React setState happens after second click

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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);
  };

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading