8

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?

Tholle
  • 108,070
  • 19
  • 198
  • 189
Wonka
  • 8,244
  • 21
  • 73
  • 121
  • 1
    Might be missing something, but why not just: `questionsList.find(question => question.id === id).question = "Is the earth flat"`? – mweststrate Sep 18 '16 at 06:28

1 Answers1

10

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);
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • Hi Tholle, yes that would work and solve this simply. But the underlying issue is when I send back the new updated object `newQuestion` from the server, (say with 10 additional fields) on top of the question/answer fields above, I want to overwrite the entire `oldQuestion` object, instead of listing each specific property of the `question` object and overwriting it one by one. Basically do it in bulk, replace/overwrite the entire `question` object with the matching `id` of `1` How can I do that? – Wonka Sep 17 '16 at 13:28
  • @Wonka Gotcha. Updated the answer. – Tholle Sep 17 '16 at 13:37