Search⌘ K

Adding Actions

Explore how to implement actions in a MobX model to manage liked images in a React Native app. Understand how to update state, use observer wrappers to trigger re-rendering, and handle observable arrays properly so they display instantly in the UI.

Implementing actions to populate our model

Let’s go back to our LikedImages model and add some real code for the addImages action:

TypeScript 3.3.4
// Adding actions to the LikedImages model
.addactions(self => ({
// Action to add a new liked image to the beginning of the imageList
addLikedImage(newImage) {
// Using unshift to add the new image to the front of the array
self.imageList.unshift(newImage);
},
//... (other actions can be added here)
}))

The actions function itself holds a reference to the entire array of liked images—this is the self keyword. In the first iteration of the MobX library, we could find uses of a known JavaScript keyword: this.

Unfortunately, this can be confusing for many developers, which is why MobX introduced self. Plus, MobX realizes that if we’re executing an action on a model, we ...