Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
Can I set a State in map function?

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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...

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda