DEV Community

Discussion on: Simpler React component design with the Chain of Responsibility pattern

Collapse
 
callmemagnus profile image
magnus

hmmm... Nice writeup but when I look at the original file content:

import React from 'react';
class Article extends React.Component {

  constructor(props) {
    super(props);
    this.state = { articles : [] };
  }

  async componentDidMount() {
    const result = await fetch('http://sample.com/');
    const articles = await result.json();
    this.setState({articles: articles});
  }

  render() {
    return this.state.articles.map( article => {
      if (!article.visible) return <React.Fragment />;
      else if (article.loading) {
        return <div className="article skeleton" />;
      }
      else {
        return (
          <div className="article">
            {article.title}
          </div>);
      }
    });
  }
}
export default Article;

I wonder a little about the need, I wonder if you over-simplified your example to not overload the article.

The first call to render will render an empty array as this.state.articles is equal to []. So article.loading will never be used.

Then, when the fetch is done, you have a list of articles assigned to this.state.articles. Before doing that, if you don't display invisible article, I would have filtered the values returned by the server. (by the way, why does the server even return those articles.)

Resulting class would be:

class Article extends React.Component {

  constructor(props) {
    super(props);
    this.state = { articles : null };
  }

  async componentDidMount() {
    const result = await fetch('http://sample.com/');
    const articles = await result.json();
    this.setState({
      articles: articles.filter(article => !!article.visible)
    });
  }

  render() {
    if (!this.state.articles) {
      return <div className="articles-skeleton-list" />
    }
    return this.state.articles.map(article => (
      <div className="article">
        {article.title}
      </div> 
    ));
  }
}
export default Article;