diff --git a/src/components/article/ArticleView.jsx b/src/components/article/ArticleView.jsx index dfc0f8b..ade5ed4 100644 --- a/src/components/article/ArticleView.jsx +++ b/src/components/article/ArticleView.jsx @@ -20,21 +20,17 @@ import ArticleViewEANs from './boxes/ArticleViewEANs'; import ArticleViewPrice from './boxes/ArticleViewPrice'; import ArticleViewLists from './boxes/ArticleViewLists'; -function viewStateFromStore(store, sku) { - const categoryState = store.getCategoryState(); - return { - article: store.getArticle(sku) ?? null, - categories: categoryState?.categories ?? null, - rootCategoryId: categoryState?.rootCategoryId ?? null, - }; -} - class ArticleView extends Component { static contextType = StorageManagerContext; constructor(props, context) { super(props, context); - this.state = viewStateFromStore(context, props.sku); + const { article, unwatch } = context.article.watch( + props.sku, + (next) => this.setState({ article: next }), + ); + this.state = { article }; + this.unwatchArticle = unwatch; } componentDidUpdate(prevProps) { @@ -42,7 +38,13 @@ class ArticleView extends Component { const { article } = this.state; if (prevProps.sku !== sku) { - this.setState(viewStateFromStore(this.context, sku)); + this.unwatchArticle?.(); + const { article: next, unwatch } = this.context.article.watch( + sku, + (updated) => this.setState({ article: updated }), + ); + this.unwatchArticle = unwatch; + this.setState({ article: next }); return; } @@ -53,9 +55,17 @@ class ArticleView extends Component { } } + componentWillUnmount() { + this.unwatchArticle?.(); + this.unwatchArticle = null; + } + handleArticleDeleted = () => { const { navigate } = this.props; - const { article, categories, rootCategoryId } = this.state; + const { article } = this.state; + const categoryState = this.context.getCategoryState(); + const categories = categoryState?.categories ?? null; + const rootCategoryId = categoryState?.rootCategoryId ?? null; const categoryId = article?.categoryIds?.[0]; if (categories && rootCategoryId != null && categoryId != null) { navigate(buildCategoryPath(categories, rootCategoryId, categoryId)); @@ -72,7 +82,10 @@ class ArticleView extends Component { render() { const { tab } = this.props; - const { article, categories, rootCategoryId } = this.state; + const { article } = this.state; + const categoryState = this.context.getCategoryState(); + const categories = categoryState?.categories ?? null; + const rootCategoryId = categoryState?.rootCategoryId ?? null; if (!article || categories == null || rootCategoryId == null) return null;