Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda