rechie
rechie

Reputation: 2209

How to update a store from other store function

I have 2 store namely AttachmentStore and CommentStore.

export class AttachmentStore {
  @observable attachments = []
}

export class CommentStore {
  @observable comments = []

  save_comment_and_attachment(comment, attachments) {
     this.comments.push(comment);
     //how can I push the attachment to the
     //attachments observable
  }

}

I know I can declare attachments as part of CommentStore observables, but is there any way I can update attachments observable from CommentStore?

Upvotes: 0

Views: 52

Answers (1)

farwayer
farwayer

Reputation: 4122

export class AttachmentStore {
  @observable attachments = [];

  @action add(attachments) {
    // ...
  }
}

export class CommentStore {
  @observable comments = [];
  attachmentStore = null;

  init(stores) {
    this.attachmentStore = stores.attachmentStore;
  }

  @action save_comment_and_attachment(comment, attachments) {
    this.comments.push(comment);
    this.attachmentStore.add(attachments);
  }
}

const stores = {
  attachmentStore: new AttachmentStore(),
  commentStore: new CommentStore(),
};
Object.values(stores)
  .filter(store => store.init)
  .forEach(store => store.init(stores));

Upvotes: 1

Related Questions