Home > database >  Can I set a State in map function?
Can I set a State in map function?

Time:10-18

This is my part of my Code that get json api from backend and rendering as list.

This is my json data example

(15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, title: '1번', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
1: {id: 2, title: '2번', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
2: {id: 3, title: '3번', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
3: {id: 4, title: '1번', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
4: {id: 5, title: '2번', content: null, createTime: '2021-10-17T14:07:02', updateTime: '202

And this is my question below


 const [postId, setPostId] = useState();



  return (
    <Container>
      {list?.map((post, idx) => (
        <Content key={idx} onClick={openModal}>
          {post.id}
          {() => setPostId(post.id)}
          {post.title}
        </Content>
      ))}

      <Modal data={postId} state={modalState} closeModal={closeModal} />
      <div ref={observer} />
      <div>{isLoading ? <Loading /> : "Data END"} </div>
    </Container>
  );
}

export default Posts

I want to set

setPostId

using value of

{post.id}

in map function but I don't know how to do that? and

{() => setPostId(post.id)}

this function is not working

help me plz

CodePudding user response:

you can do -

{
  list?.map((post, idx) => {
    setPostId(post.id);
    return (
      <Content key={idx} onClick={openModal}>
        {post.id}
        {post.title}
      </Content>
    );
  });
}

But I'm not sure why you want to do it this way...

CodePudding user response:

map can't change the state of the array because it return a new array with the new state, if you want to change the some data in the array itself you need to use list.forEach instead

  • Related