0

when I run the following function, I get an error. What is the reason ?
Error : Attempted to assign to readonly property.

State:

const [editing, setEditing] = useState({
    id:0,
    coordinates: [
        {
            "latitude": 37.42745040252729,
            "longitude": -122.08988696336746,
         },
         {
            "latitude": 37.41441869485446,
            "longitude": -122.09136821329594,
         },
         {
            "latitude": 37.41091893789202,
            "longitude": -122.0801817253232,
          }
    ],
    holes: [],
});

Function :

const onPress = (e) => {
    const newCoordinates = editing.coordinates;
    newCoordinates.push(e.nativeEvent.coordinate);
    setEditing({
       id: 0,
       coordinates: newCoordinates,
       holes:[]
    });
});

Error line :

const newCoordinates = newCoordinates.coordinates;

1 Answers1

2
const onPress = (e) => {
  setEditing({
    id: 0,
    coordinates: [...editing.coordinates, e.nativeEvent.coordinate],
    holes:[]
  });
});

Just use spread operator and always give new [] or {} reference when updating the state. Plays well with React since React uses variable references to follow and update the rendering.