Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

295
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!