First of all, I am not experienced React developer. Just let you know.
I have a store:
import {observable, action, reaction, computed, autorun} from 'mobx';
import scrollTo from 'react-scroll-to-component'
class ActivePostsStore {
@observable _posts = new Map()
@observable _visiblePosts = new Set()
@computed get visiblePosts() {
return this._visiblePosts
}
@action
addPost(uuid, ref) {
// console.log('add post')
this._posts.set(uuid, ref)
}
@action
scrollToPost(uuid) {
// console.log('scroll to post')
scrollTo(this._posts.get(uuid), {})
}
@action
addVisiblePost(uuid) {
console.log('add vis post', this._visiblePosts.values())
this._visiblePosts.add(uuid)
}
@action
removeVisiblePost(uuid) {
console.log('rem vis post', this._visiblePosts.values())
this._visiblePosts = new Set([...this._visiblePosts].filter(el => el !== uuid))
}
// reacts = reaction(() => this._visiblePosts, () => console.log('===='))
// reactToVisiblePosts() {
//
// }
}
const store = new ActivePostsStore()
export default store
My first problem, that I can pass store through Provider in my Layout Component or _document.js (I use Next.js).
/*Doesn't work. In root layout*/
<Provider store={ActivePostsStore}>
<Content />
</Provider>
Every time when I tried to use Provider
I got my store undefined. In RootLayout or _document.js too. Sure, I provided @observer
annotation for component which use store. But store is still undefined.
Then, I tried to use @inject('activePostsStore')
result is Error, that tells me, like I didn't provide any store at all. But, actually, I did.
SO! I decided to inject it directly like:
@inject(() => ({
store: ActivePostsStore
}))
@observer
Finally, I can use actions to add or remove elements for visiblePosts
(i log it). BUT! My store props does not react at all, if I change state of store. For example it does not react to adding new entries to visiblePosts. Or it even can be undefined if I reload page. My code for component is:
render() {
const {classes} = this.props
return (
<div className={classNames(classes.postsTree)}>
{this.props.store.visiblePosts}
{this.state.groupedDates !== undefined && this.state.groupedDates.map(([date, posts], index) =>
<PostsTreeGroup
active={_.some(posts.map(([uuid]) => uuid), uuid => this.props.store.visiblePosts.has(uuid))}
key={date}
date={date}
posts={posts}/>
)}
</div>
)
}
Can somebody help me to make things works, please!