Search code examples
reactjstypescriptreact-statereact-lifecycle

Implementing loader in React


I've trying to implement a loader which is shown if the component didn't receive data from API yet. Here is my code:

import React, {Component} from 'react'

import './news-cards-pool.css'

import NewsService from '../../services/news-service'
import NewsCard from '../news-card'
import Loader from '../loader'

interface NewsCardsPoolProps {
    currentCategory: string
}

interface NewsCardsPoolStates {
    newsList: Article[],
    currentCategory: string,
}
interface Article {
    title: string,
    description: string,
    url: string,
    image: string
}

export default class NewsCardsPool extends Component<NewsCardsPoolProps, NewsCardsPoolStates> {

    newsService = new NewsService()

    state = {
        newsList: [],
        currentCategory: ''
    }

    componentDidUpdate(prevProps: Readonly<NewsCardsPoolProps>) {
        if(prevProps.currentCategory !== this.props.currentCategory) {
            this.updateNews()
        }
    }

    componentDidMount() {
        this.updateNews()
    }

    updateNews(){
        this.newsService.getByCategory(this.props.currentCategory).then((list: Article[]) => {
            console.log(list)
            this.setState({
                currentCategory: this.props.currentCategory,
                newsList: list
            })
        })
    }

    renderItems(newsList: Article[]){
        const itemsList = newsList.map((article: Article) => {
            return(
                <div className="col-sm-12 col-md-6 col-lg-3 card-container">
                    <div className="card">
                        <img src={article.image} alt="icon" />
                        <div className="info">
                            <h5><a href={article.url}>{article.title}</a></h5>
                            <p>{article.description}</p>
                        </div>
                    </div>
                </div>
            )
        })

        return itemsList
    }

    render() {
        const { newsList } = this.state
        if (newsList === []){
            return <Loader />
        }

        return this.renderItems(newsList)
    }
}

The problem is that this equation always gives false, however, console.log() shows that array is empty, what am I missing? The same thing happens even if .setstate for newsList everywhere is set to []. I'm using React with typescript. Thanks in advance!


Solution

  • You can also create a specific state which will handle this kind of case. What you do is:

    1. Add another state and set it to true.

    Example:

    state = {
      newsList: [],
      currentCategory: '',
      loadingData: true
    }
    
    1. Set it to false when data is loaded.

    Example:

    updateNews(){
        this.newsService.getByCategory(this.props.currentCategory).then((list: Article[]) => {
        console.log(list)
        this.setState({
          currentCategory: this.props.currentCategory,
          newsList: list,
          loadingData: false
        })
      })
    };
    
    1. In your if statement, make sure loading is false before continuing.

    Example:

    const { newsList } = this.state
      if (newsList.loadingData){
        return <Loader />
      }