Reactjs - adding loading state

Hello,
I’ve been trying to add a loading state before my data arrives to the browser. I’ve created a loading state of true and a setState of loading to false, that way the loader/spinner is displayed then removed after the data is received. Here is my code thus far

import React, {Component} from 'react';
import axios from 'axios'

export default class Posts extends Component {
    constructor(props) {
        super(props);
    
        this.state = {
            posts: [],
            loading: true;
        }
    }

    componentDidMount() {
        axios.get(`https://apiurl.com`)
        .then(res => {
            const posts = res.data;
            this.setState({ posts });
            loading: false
        })
    }    
    
    render() {
        const posts = this.state.posts.map((item) =>
                <div>
                   <p className="name">{item.name}</p>
                </div>
        );

        return (
        {
            this.state.loading &&
            <span class="sr-only">Loading...</span>
        }
            <div>
                {posts}
            </div>
        )
     }
}

I’ve been getting errors in my return() about

  {
       this.state.loading &&
        <span class="sr-only">Loading...</span>
  }

Any suggestions? Thanks in advance!!!

Hi @Liamgrossman, you can only return a single element from the render() function, yo you’ll need to wrap it in a container element; this can also be a fragment though which was introduced for exactly this purpose:

return (
  <>
    {this.state.loading && <span class="sr-only">Loading...</span>}
    <div>{posts}</div>
  </>
)

Thank you so much! This worked perfectly!!!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.