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

React Typescript: Array does not map through all items

I have following Table / Array:
enter image description here

If I press the blue button, then all items with the same group as the record should change the Status (Gratis).
But now it just change the Value of the Record and all items above it. As an example, if I press the Button on Record No. 1 then itselft and all above (No. 0) get an change of the Status (Gratis).

Following code im using to go through the array and change the Status:

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

private _updateFreeStatus = (record: QuestionModel): void => {
        fetch('api/Test/UpdateGratisStatus', {
            headers: { 'Content-Type': 'application/json' },
            method: 'PUT',
            body: JSON.stringify({
                'group': record.group,
                'free': record.free,
            })
        });
        this.state.question.map(item => {
            if (item.group === record.group)
            {
                item.free = !record.free;
            }
        });
    }

>Solution :

  1. do not mutate the state
  2. create a copy, and use setState

Use

const updatedQuestions = this.state.question.map(item => {
  if (item.group === record.group) {
    return {
       ...item,
       free: !record.free
    }
  }
  return item;
});

this.setState({question: updatedQuestions});
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