reactjsaxiosloadingjsonplaceholder

Best way to handle component loading in react


I've an app that gets posts from JSONPlaceholder. It has an initial state of posts: []. It then calls:

this.setState({posts})

If I want to render loading... before the component receives the posts, is it better to say:

if (!this.state.posts.length) // Do something

or it's better to add loading: true to initial state then said this if the component received data without error:

if(!this.state.loading) // Do something

Solution

  • First, as the comment said, use a single boolean type state is better than use a changeable condition everywhere.

    If you want to add some loading animation, I've tried Material-UI processing sometimes and it's convenient.

    And the usage is quite simple in this situation. Add a conditional rendering and it's done.

    import { CircularProgress } from '@material-ui/core';
    ...
    render() {
      const { loading } = this.state;
      return (
        ...
        {loading ? <CircularProgress /> : <YourComponent /> ... 
        ...
      )
    }