How can I observe any change (property added, removed or changed) in a mobx observable map? - mobx

class FilterCriteria {
#observable filter = new Map();
}
let criteria = new FilterCriteria ();
// setting up a reaction when something in the filter changes
// (property added, removed, or changed)
reaction(()=>criteria.filter, data => console.log(data.toJSON()));
criteria.filter.set('name', 'John'); // setting a new property.
I would expect the above code to print out { 'name': 'John' }, but it seems that the reaction is not running.
I suspect that I set up the reaction in the wrong way. I want to react whenever a new key is added, an existing key is removed or a key value is changed. I don't know the keys or values at compile time.
How am I supposed to do that?
UPDATE
I changed my code to
class FilterCriteria {
#observable filter = new Map();
#computed get json(){ return this.filter.toJSON(); }
}
...
reaction(()=>criteria.json, data => console.log(data));
and now it seems to work properly. The reaction sideffect is executed whenever I add, remove or change a value in the Map.
So the question is why the reaction did execute in the second but not in the first example?
UPDATE 2
I changed my code again for a second time. I reverted to almost the first version but this time instead of reacting on criteria.filter and logging data.toJSON(), i react on criteria.filter.toJSON() and I log data (toJSON is moved from the sideffect to the value being watched). This time the reaction runs normally.
class FilterCriteria {
#observable filter = new Map();
}
reaction(()=>criteria.filter.toJSON(), data => console.log(data));
Again, I don't understand why. If criteria.filter is not an observable in itself then how does the watched expression is reevaluated when something inside criteria.filter is changed?
UPDATE 4 (hope the final one) SOLUTION
According to MobX documentation, mobx reacts to any existing observable property that is read during the execution of a tracked function.
reaction side-effect executes when the observable property changes. In my example, when reacting to criteria.filter , the observable property that is read here is filter, but the filter itself never changes. It is the same map always. It is the properties of filter that change. So the reaction is never run for criteria.filter.
But when I react on criteria.filter.toJSON() or mobx.toJS(criteria.filter), the reaction is executed correctly.
So why is that? criteria.filter doesn't change, and toJSON is not an observable property. It is a function. same for mobx.toJS. It seems no properties are read here. But this is not correct. As the documentation states (but not so emphatically), the properties of criteria.filter are indeed read when toJSON or mobx.toJS is executed, because both functions create a deep clone of the map (thus iterating over every property).
Now, in the beginning, the Map did not contain any property. So how is it that newly added properties are tracked, since they did not exist (to be read) when tracking begun? This is a map's feature. Maps provide observability for not yet existing properties too.
In MobX 5 you can track not existing properties of observable objects (not class instances) too, provided that they were instatiated with observable or observable.object. Class instances don't support this.

In mobx you have two options when you want to observe changes to something that is observable. reaction and observe. Reaction allows you to specify when you want some function to be called when a specific aspect of the observable changes. This could be changes to an array length, keys, properties, really anything. observe will trigger some function any time that the observable has changed.
I suspect the reason that your reaction hasn't been triggered is because of the first function. () => criteria.filter. This will not be triggered when a key is added/removed or a value changed. Instead, it will be triggered when filter actually changes. And since filter is really a reference to the Map, it will never change, even when the Map itself changes.
Here are some examples to illustrate my point:
If you want to trigger a reaction when a key has been added or removed, you may want your function to be:
() => criteria.filter.keys()
The result of this function will be different when a key has been added or removed. Similarly, if you want to trigger a reaction for when a value has been modified, something like this should work:
() => criteria.filter.values()
So some combination of those two should be what you need to listen to changes to keys/values. Alternatively, you could use observe, which will trigger on every change and require you to check what has changed to ensure that your specific conditions have been met to warrant calling a function (ie. key/value change)
UPDATE: Here is an example that illustrates the problem
#observable map = new Map();
Lets say that the value of map in memory is 5. So when you check map === map, it is equivalent to 5 === 5 and will evaluate to true.
Now, looking at the first code snippet you posted:
reaction(() => map, data => console.log(map.toJSON()));
Every time you add/remove a key or change a value, that first function will run. And the result will be 5, since that is what we said the value in memory is for this example. It will say: the old value is 5, and the new value is 5, so there is no change. Therefore, the reaction will not run the second function.
Now the second snippet:
reaction(() => map.toJSON(), data => console.log(data));
At first the result of the function will be: {} because the Map is empty. Now lets add a key:
map.set(1, 'some value');
Now, the result of the first function will be:
{"1": "some value"}
Clearly, this value is different than {}, so something has changed, and the second function of the reaction is called.

Related

Chart data of object gets overwritten, but only the first object that is interacted with is affected

Here is this a code sand box proving and showcasing this issue: https://codesandbox.io/embed/ql4rm9734w?fontsize=14
When a user clicks on a button in the app's. A widget is meant to show the data of that object. The the object contains an array that is used to produce a graph. The first object's button click seems to display and function correctly. So does the second and the third. But when the first objects button is clicked again the chart data property of the object is overwritten with the chart data of the previously clicked object.
The application has been built in Vue.Js, with Highcharts, and Highcharts official Vue wrapper rendering the charts. The data is stored in a Vuex store.
The page gets populated with a button for each object. When a objects button is clicked a custom event is fired containing the object data. The object click event handler mutates the store passing the object to the store to be saved as a active marker object. The object Widget that displays the data to the user gets its data from the stores active marker object.
this process works fine for every other object that uses this system. It also only ever effects the first object clicked, all subsequent objects are unaffected and work correctly.
I have tried the following with no luck
Vue dev tools and debugging, shows the symptoms of the error but does not point to where the error takes place.
I have tried making the data property a pseudo private property that can only be accessed with setters and getters. The setter is never called.
Added second property in the class to act as a not modified storage variable for the original data given at construction time. This second property also gets modified.
When examining the store in depth, it looked like the object array in the store was not affected by the bug. However when refactored to use the object from the store directly the bug is still there.
I tried to separate out the data into a separate state property that is not related to the object in any direct way... still the same bug.
I also tried with a every small data array (15 elements) still the bug persisted.
I have even built a mini replica project in the hopes that at the smallest scale the bug does not appear and hopefully it would be a silly typo or something... but again, even this mini version of my app still shows the bug. the Mini version can be found here: https://github.com/ChadRoberts21/ChartMapBug
Built a more refined smaller example: https://codesandbox.io/embed/ql4rm9734w?fontsize=14
The code is available from https://codesandbox.io/embed/ql4rm9734w?fontsize=14
I expect that the correct chart data is always shown in the object widget and for the object to not have its data property overridden at all unless I expressly choose to do so in a Vuex mutation.
The problem occurs, because of fact that the Highcharts mutates the data, which not exactly complies the Vue conceptions. Generally, if you are able to avoid the data mutation you shouldn't do that at all. I've just answered that question directly on the highcharts-vue repository, so there you can find more specific description about why the issue occurs.
In essence (for another users searching for the answer on that question), the best way out of the problem will be to apply a spread operator when assigning a new data to series:
FooWidget.vue (chartOptions() computed property part)
series: [{
showInLegend: false,
type: "column",
color: this.foo.colour,
data: [...this.foo.data],
pointInterval: this.foo.interval,
pointStart: this.foo.startPoint,
gapSize: 4,
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
}
},
threshold: null
}]
Live example: https://codesandbox.io/s/w2wyx88vxl
Best regards!
I think the problem is you are using computed for fetching data. when you pass data in click event it's actually updated foos array of the store(reference of state.foos). so when you click on test2 the data in the store of foos array is updated.
Try to console log foos array in store setActiveFoo method you can see that foos array is updated with other values.
setActiveFoo(state, payload) {
console.log("In store foos")
console.log(state.foos);
state.activeFoo = payload;
}
Try this code. I think you need to send the copy of foos array in computed it will solve the problem.
computed: {
foos() {
return JSON.parse(JSON.stringify(this.$store.getters.foos));
},
activeFoo() {
return JSON.parse(JSON.stringify(this.$store.getters.activeFoo));
}
}

V-Model not cleansed when adding Object to array (Vue-Js)

I'm trying to add objects (simple key-value pairs) to a list.
However, the v-model is still bound to the previously added objects, so if I add "ObjectOne" vith "ValueOne", then try to add "ObjectTwo" with "ValueTwo", "ObjectOne" gets edited AND "ObjectTwo" gets added.
I am by no mean an expert in Javascript, so it might not be related to VueJS.
I can obviously make this work with a method per list .
The point is that my model has multiple lists of key value pair to be edited, so I tried making a generic method :
addToList: function(value, list){
console.log("Adding " + value + " to list "+list);
list.push(value);
value={};
},
This method works if used on "simple" lists (like an array of string), but not on "objects" list.
My guess is that as I try to clean "value" instead of "this.value", the reference still points to the same object, but since I don't know what "value" will be when called, I don't know how to do this.
Here is the fiddle with a re-creation of my issue.
My objective would be to be able to use the "addToList" function to add to any list, without having to re-write a function for each list.
Thank you for your help.
The above behaviour is because you are updating the value of same object whenever you add a new todo task.You need to set your object again to add new values as below.
addToList(value, todos){
this.todos.push(value);
this.anotherTodo={ text:'',
done:'false'}
}
Working fiddle here.
I post this as an answer, but if someone has a better way to do it, I'm all hear.
I solved the way by adding a watch on my list. When the list changes, I clean the model object that's added to it.
In my production work, I had to add a computed property, since I can't add a watch on an object's property, then a watch on said computed property :
watch:{
todos(){
this.anotherTodo={};
},
fiddle as demo

Vue: Forcing child component to react to changes in its prop (which is a dictionary)

I am currently generating a table which lists problems encountered during the selected test using a component generated with this code:
<tr is="entry" v-for="problem in problems" :key="problem.id" v-bind:foo="problem"></tr>
Each problem corresponds to an item whose relevant information is contained within the problem dictionary and referenced in the first few columns of the table. Since the same item can have multiple problems, the same item can appear in multiple rows of the table. Now, each row features some buttons which allow you to modify the underlying item so as to fix the problems.
Whenever I modify one of those underlying items I need to modify it in all the rows, which i do by calling a function in the parent component, but modifying the data inside of the dictionary does not seem to trigger any of my watches or computes inside of the child component, which currently looks something like this:
Vue.component('entry', {
props: ['foo'],
data: function(){
//does some computations
return data
},
watch:{
foo: function(){
this.recompute_entry()
},
},
methods:{
//various methods, including:
recompute_entry: function(){
//updates the data according to changes brought to the entry
},
},
});
I have attempted to include a different prop which i could bind to an entry in a list in my parent component but, besides being pretty clunky, that didn't end up working either, which makes me think I might've gotten something wrong with my component.
Ultimately, I have relied on the fact that v-for iterates through my list in an orderly fashion, which combined with the fact that I generate no other children in my parent component means that a child component would have the same index in my component's children array as it would in my problems array. Therefore I can use this:
this.$children[problem_index].recompute_entry();
Which kind of feels hack-ish and unreliable, but actually works, for once. Is there no alternative safer method to recalculate my child components based on changes made to their props? I really feel there has to be.
I probably would need to see the exact implementation but it sounds like you need to clone your dictionary to trigger the prop change, ie:
let newProblem = Object.assign({}, this.problem);
// change any nested property
newProblem.some.value = 1
// assign back the cloned and modified dictionary
this.problem = newProblem

How to properly select from multiple Redux-slices in mapStateToProps?

My Redux store is normalized, i.e. it's quite flat and each entity type has it's own slice.
Here is a simplified example of my Redux store:
drawings
1: {name:'D1', thumbnailId: 33}
2: {name:'D2', thumbnailId: 34}
thumbnails
33: {filePath: 'path to local file'}
34: {filePath: null (i.e. needs to be downloaded)}
The listview that shows the drawings whith respective thumbnail needs to be re-rendered when:
Changes in drawings-slice occurs, i.e. new, removed or updated drawings
Changes in any of the referenced thumbnails occurs, i.e. thumbnail 34 eventually gets downloaded (download is handled async by a Redux-Saga)
My current mapStateToProps is obviously flawed, as it does excessive selections from the Redux store. This happens before the actual view gets hold of its new props, so I cannot control this from shouldComponentUpdate.
There are several places in my app where I need a better solution for this.
Here is my flawed mapStateToProps (I'm using Immutable.js):
(state, ownProps) => {
const drawings = selectProjectDrawings(state, ownProps.projectId).map(drawing => {
const thumbnailFileGuid = drawing.get('thumbnailFileGuid');
if (!thumbnailFileGuid) return drawing;
const filePath = selectFile(state, thumbnailFileGuid).get(THUMBNAIL_FILE_PATH_FIELD);
return filePath ? drawing.set('_thumbnailFilePath', filePath) : drawing;
});
return {
drawings: drawings
};
}
Edit:
A really bad thing with my current solution is that I'm creating new drawing object by augmenting them with _thumbnailPath. This means that I cannot compare the object references in shouldComponentUpdate, as the reference is always altered.
Being able to compare object references is one of the main argument for not mutating the objects, but I have thrown away this opportunity with my flawed solution.
I would suggest placing this logic behind a selector. reselect is a selector memoization library which means that it will do a deep compare of the values for you and if the returned object and all the properties within stay the same, (including deep tree like structures) then it will return the original object.
React then will notice this is the same object instance (not a new one) and not re-render. It is OK if you recreate the drawing object within the selector, since you are not capturing this in any persistent state.
Side note: As your app grows, you will notice that all connected components will get mapStateToProps called even if it has nothing to do with it, therefore using a memoized selector really helps here. Otherwise your componentShouldUpdate gets complex real quick.

Mobx Autorun in practice

I'm trying to get Mobx's autorun to work correctly.
My use case is I have one model that I like to serialize (or dehydrate) when it is changed and add that information to another model's data. This brings me rudimentary time travel of model states. Both are observables.
Edit: Idea in model separation is that one is app's data model and other should be completely separate library that I could use from the app. I need to track changes in the app regularly, but show UI for the state tool on the same page.
Now, autorun seems to make its own inferences of what I'm actually tracking. When I moved the model instance inside observing model's instantiation, autorun wasn't called anymore when changes happened. When model instance was created on the module top level, it worked as I expected. This was when I only changed one property of observing model (the one that gets changed by every autorun call). When I tried changing two things at once in the observing model, autorun was now called for these changes also, leading to a unending cycle (which Mobx caught).
I'd like to know how to express what I'm tracking with autorun function be more explicit, or wether there are other ways to keep track of model changes and update other model when anything happens.
Edit with code example.
This is what I did (greatly simplified):
class DataModel {
#observable one_state = null;
}
class StateStore {
#observable states = [];
}
let data = new DataModel();
let store = new StateStore();
autorun(() => {
store.states.push(data.one_state);
console.log("new data", toJSON(store.states));
});
data.one_state = "change 1";
data.one_state = "change 2";
And this creates circular dependency because autorun gets called for both original data model change and the resulting store change, whilst I'm only interested in tracking changes to the former.
Edit with working result:
class DataModel {
#observable one_state = null;
}
class StateStore {
#observable states = asFlat([]);
}
let data = new DataModel();
let store = new StateStore();
autorun(() => {
store.states.push(data.one_state);
});
data.one_state = "change 1";
data.one_state = "change 2";
As per #mweststrate answer, using asFlat with store's states variable and removing the logging from autorun broke the problem cycle.
It is a bit tough to answer this question without any real code. Could you share some code? But note that MobX works best if you make a small mind shift: instead of imperatively saying "if X happens Y should be changed" it is better to say "Y can be derived from X". If you think along those lines, MobX will really start to shine.
So instead of having two observable models, I think one of them should be a derivation of the other (by using computed indeed). Does that make sense? Otherwise, feel free to elaborate on your question a bit more :)
Edit:
Ok thanks for the code. You should remove the log statement to avoid it from looping; Currently you log the states model, so each time it changes, the autorun will run, adding the first item (again!), changing the stateModel etc...
Secondly I'm not sure whether the states list should be observable, but at least its contents should not be observable (since it is a snapshot and the data per state should not change). To express that, you can use the asFlat modifier, which indicats that the states collection should only be shallowly observable: #observable states = asFlat([]).
Does that answer your question?