Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splice an array in React keeps rerendering

In the update(changeProps) function, I have something like this:

 update(changedProps) {
      if (this.person) {
        this.__arr = ['hi', 'hi', 'hi'];
      } else {
        this.__arr = ['bye', 'bye', 'bye', 'bye'];
      }

    if (this.__hello) {
      this.__arr.splice(1, 0, 'hello');
    }

    super.update(changedProps);
  }

Say this.person is true, when I click elsewhere and the page rerenders, it becomes

this.__arr = ['hi', 'hello', 'hi', 'hi']

Then when it rerenders again: this.__arr = ['hi', 'hello','hello', 'hi', 'hi']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It keeps adding to the array after each rerender. Same for if this.person is not true. How do I make it so it only adds it once?

If I did something like this: this.__arr = [...this.__arr, 'hello'], it can add it to the end, but I want to add an element to index 1

>Solution :

Two things:

  1. Don’t mutate:
    if (this.__hello) {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
  1. Do you want to do this every time the component updates, or just once?
    if (this.__hello && this.__arr[1] !== 'hello') {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading