0

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!

Max Pan
  • 137
  • 1
  • 7

3 Answers3

2

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 />
  }
Westman
  • 202
  • 2
  • 4
1

Arrays in javascript are objects, which are saved on the heap. And when you are using the "===" (strict equality operator) you are asking if they are really the same objects, they are not, because they will be saved onto different memory addresses.

UsenewsList.length === 0 instead to check if the array is empty

With some tricks you can use type-coercion but it is not best practice. (loose equality operator "==" does type coercion)

1
[] === []

or

<<everything>> === []

return false

except

const a = []
a===a

will return true

read more in value versus reference

Acid Coder
  • 2,047
  • 15
  • 21