DEV Community

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

Collapse
 
xavios5 profile image
Xavios

Hi guico33,

Thanks for taking the time to read the post, and also thanks for the feedback! Considering the above example, what would be the correct functional way to approach that (investor data table cell logic) problem? I really would like to know, and next time utilize it!

Cheers,
Xavios

Collapse
 
chaseholdren profile image
Chase Holdren
import React from "react";

class ArticleList 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 });
  }

  renderArticle = article => {
    if (!article.visible) return <React.Fragment />;

    if (article.loading) return <div className="article skeleton" />;

    return <div className="article">{article.title}</div>;
  };

  render() {
    return this.state.articles.map(renderArticle);
  }
}

export default ArticleList;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wnemay profile image
Wayne May πŸ‡ΏπŸ‡¦πŸ‡ΊπŸ‡Έ

You will find that the community is alienating with OOP, at least when it comes to the react framework.

Collapse
 
guico33 profile image
guico33

Not that much to be done given the first code snippet is already very straightforward.
You may create a stateless Article component that will take care of rendering one article.
Instead of classes you can use function components (with hooks to manage state and side effects).
You could encapsulate the fetch logic into a custom hook but that's already overthinking it imo.