Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MobX - Replacing item in observable array?

Please correct me if I am wrong, but currently this is not possible using replace, as replace would replace the entire observable array and map should be used instead?

I have an observable array like this:

@observable questionsList = [];

On server call it gets populated with 2 objects, each with a distinct id field, so it'll look like this:

@observable questionsList = [
                             {id: 1,
                              question: "Is the earth flats?",
                              answer: "Some long answer here..."
                             {id: 2,
                              question: "Does the moon have life?"}
                              answer: "Some long answer here..."}
                            ];

So the question with id of 1 has a typo which needs fixing, should be Is the earth flat?

Given the following:

const newQuestionId = 1;
const newQuestion = "Is the earth flat?"
const oldQuestion = this.questionsList.find(question => question.id === newQuestionId);
oldQuestion.replace(newQuestion) // Would be nice if this syntax worked

Now I have the correct oldQuestion but how can I replace it in the questionList array with the new question? I tried replace, but it didn't work. Is map the only way? If so I am not sure how to get map to work as I've only worked with observable arrays.

How can I accomplish this using MobX?

like image 607
Wonka Avatar asked Sep 17 '16 05:09

Wonka


1 Answers

Each property of the observable object will in turn be observable, so you could just overwrite the string:

const newQuestionId = 1;
const newQuestion = "Is the earth flat?"
const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
oldQuestion.question = newQuestion;

If you have additional fields in the new question object that you would like to use instead, and make these new fields observable as well, you could use extendObservable:

const oldQuestion = this.questionsList.find(q => q.id === newQuestionId);
extendObservable(oldQuestion, newQuestionObject);
like image 194
Tholle Avatar answered Oct 21 '22 08:10

Tholle