Home > Software design >  How can I use useState to modify an array in order to a constant in React
How can I use useState to modify an array in order to a constant in React

Time:07-30

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)}
/>

...
    )
    }

CodePudding user response:

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;
  }))
}, []);

CodePudding user response:

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.

  • Related