Hi I'm a beginner in React. I am developing my task and I need to declare an array with null values:

this.state = {
  position: [null,null,null,null,null,null,null,null]
};

After that I assign some values to this array, but my application does require that every pool can only be changed once. Regards

2 Answers

1
Jonas Wilms On Best Solutions

If you change the task to position can only be changed from null to another value and not to null again, then it gets easy

  setPool(i, pool) {
    if(pool === null) return; // prevent that any position gets set back to `null`

    this.setState(({ position }) => {
      if(position[i] !== null) return; // prevent that a pool gets set twice
      return { position: position.map((v, i2) => i === i2 ? pool : v) };
    });
 }
0
Maheer Ali On

You can use Proxy for this

let arr = Array(5).fill(null);
const validator = {
  set:function(obj,prop,value){
    if(obj[prop] !== null) throw "You can't change it again"
    else obj[prop] = value;
  }
}
var p = new Proxy(arr, validator);
p[1] = 2; //the element is successfully changed
console.log(JSON.stringify(p))

p[1] = 3; // changing again throw error.