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

296
Vistas
How can I use useState to modify an array in order to a constant in React

I have an array object value in a constant called room.

room = [
    {name: "buger", placeId: 252}
    {name: "pack", placeId: 253}
    {name: "apple", placeId: 254}
    {name: "peach", placeId: 255}
]

At this time, I want to change the value of name in the room by using the onChangeroom function whenever I write a character in TextInput.

So, when I run setRoom in the onChangeRoom function and attach ["name"], an Unexpected Token error appears.

How do I change my code to change the name of the room?

Below is my code.

const [room, setRoom] = useState(
targetFarm.children.map((v) => ({ name: v.name, placeId: v.placeId }))
)


const onChangeroom = useCallback((index) => (text) => {
    setRoom({ ...room, [index]["name"]: text });      // << this might cause error
}, []);


{targetFarm.children.map((item, index) => {
    return (
<TextInput
style={{ backgroundColor: 'orange' }}
value={room[index]["name"]}
onChangeText={onChangeroom(index)}
/>

...
    )
    }
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can get index in map function. After you've got an index, then you can update.

Let me show an example:

const [room, setRoom] = useState([
    ...targetFarm.children
]);

const onChangeroom = useCallback((index, text) => {
    
    setRoom(room.map((pr, i) => {
    if(i === index) {
      return {
        ...pr,        
        name: text
      }
    }
    else return pr;
  }))
}, []);
about 4 years ago · Santiago Trujillo Denunciar

0

Try passing both index and text to onChangeRoom(text, index) And modify the useCallback hook to look like this (notice that both arguments are passed to the second function inside the hook):

const onChangeroom = useCallback(() => (text, index) => {
    setRoom({ ...room, [index]["name"]: text });
}, []);

Let me know it this works for you.

about 4 years ago · Santiago Trujillo 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