1
\$\begingroup\$

Looking for some ideas as to how to improve the below react component.

var JSON_URL = "https://api.example.io/comments.json";
class CommentList extends React.Component {  
    constructor() {    
        super();    
        this.state = { comments: [] }  
    }  
    componentDidMount() {    
        $.ajax({      
            url: JSON_URL,      
            dataType: 'json',      
            success: function(data) {        
                this.setState({comments: data.comments});      
            }.bind(this)    
        });  
    };  
    render() {    
        return <ul> {
            this.state.comments.map((comment) => {
                return <li>{comment.body}—{comment.author}</li>;                    
            })}
       </ul>;  
    }
}
React.render(<CommentList />, document.getElementById('root'));
\$\endgroup\$
1
\$\begingroup\$

ES6 arrow function

Nice work utilizing functional programming (i.e. .map()) and the arrow function. One improvement here is that there isn't much of a need for a code block (i.e. { ....}) and return statement. So the callback to .map() in the render method can be reduced to a single line like below:

render() {    
    return <ul> {
        this.state.comments.map((comment) => <li>{comment.body}—{comment.author}</li>)
    }</ul>;  
}

jQuery - just for AJAX requests?

It appears that the only jQuery functionality used is its AJAX wrapper (i.e. $.ajax()). If that is all jQuery is used for, consider using a different technique like the fetch API (read this article for more info).

componentDidMount() {  
    fetch(JSON_URL)
    .then(response => response.json())
    .then(data => this.setState({comments: data.comments}));    

See this plunker for a demonstration.

Update

It has been mentioned that the fetch API has no support for aborting the request. If that is desired, there are other alternatives like Superagent (recommended by you might not need jQuery). See this updated plunker for an example of using superagent with its abort method in the componentWillUnmount method.

\$\endgroup\$
  • \$\begingroup\$ Unfortunately fetch doesn't support aborting ajax requests. In the case of this component, it makes sense to abort the request during componentWillUnmount if it didn't finish. \$\endgroup\$ – Brad M Oct 18 '17 at 21:15
  • \$\begingroup\$ apparently there are new developments... see this post... sure I see that it is only supported in FF but hopefully others soon... \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Oct 18 '17 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.