I'm new to Mobx but so far it's been working great and I've managed to get pretty far. I have a react-native application with mobx, and mobx-persist. I'm using axios to pull posts from a Wordpress site. The functionality that I'm trying to improve is an "add to favorites" feature.
Here's my PostsStore:
export default class PostsStore {
// Define observables and persisting elements
@observable isLoading = true;
@persist('list') @observable posts = [];
@persist('list') @observable favorites = [];
// Get posts from Wordpress REST API
@action getPosts() {
this.isLoading = true;
axios({
url: 'SITE_URL',
method: 'get'
})
.then((response) => {
this.posts = response.data
this.isLoading = false
})
.catch(error => console.log(error))
}
// Add post to favorites list, ensuring that it does not previously exist
@action addToFavorites(id) {
if (this.favorites.indexOf(id) === -1) {
this.favorites.push(id);
}
}
// Remove post from favorites list, ensuring that it does indeed exist
@action removeFromFavorites(id) {
if (this.favorites.indexOf(id) !== -1) {
this.favorites.remove(id);
}
}
}
In my Favorites component, which is intended to render a button to add or remove from favorites, I thought that using an @computed function would've been preferred to determine if the current post being rendered has an 'id' that has been added to the observable 'favorites' array. However, it seems that an @computed function is not allowed to take arguments (a minimum parameter would be the post's 'id' to evaluate if it is in the favorites observable array. I can accomplish the test using an @action but that doesn't seem to update the rendered screen immediately which is the objective. As the code below demonstrates, I'm forced to perform the test with an 'if' statement in the component render.
render () {
if (this.props.postsStore.favorites.includes(this.props.item.id)) {
return (
<Button
onPress={() => this.props.postsStore.removeFromFavorites(this.props.item.id)}
title="★"
/>
)
}
Does this affect my application's performance? Is there an @computed way to do what I want? Should I just not worry about this since it's kinda working?