Search code examples
reactjsconditional-statementsrender

React.JS Conditional Render is Not Working?


i have 2 states "loading" and "data". i want to conditional render

1)if data array is empty = "loading2" 2)and if loading is true= "loading"

actually, 2 states are working well. Data state update 1-2 seconds later. but the conditional render is not working

line 64 is not will update but line 70 is updated well.

enter image description here

        import React, { useState, useEffect } from 'react';
    import axios from 'axios'
    import Pagination from '../Components/Listing/Pagination';
    import { useLocation } from "react-router-dom";
    import ArticleContainer from '../Components/Listing/ArticleContainer';

    export default function Listing() {
        const [data, setData] = useState([])
        const [loading, setLoading] = useState(true);

        const [currentPage, setCurrentPage] = useState(1);
        const [lastPage, setLastPage] = useState(1);
        const [nPages, setNPages] = useState(1);
        
        const [recordsPerPage] = useState(10);

        
        
    function getParam (){
      
      const urlParams = new URLSearchParams(window.location.search);
      setCurrentPage(parseInt(urlParams.get('offset'))) 
      
    }
        
        useEffect(() => {
          getParam();
          console.warn("datar",data)
          setLoading(true);
            axios.get('https://dummyblog.cengizilhan.com/wp-json/wp/v2/posts?page='+currentPage)
                .then(res => {
                        setData(res.data);
                        setLastPage(res.headers['x-wp-totalpages']);
                        setLoading(false);
                        console.warn("datar2",data)
                        //res.headers['x-wp-total'] total records
                    })
                    .catch(() => {
                        console.error('There was an error while retrieving the data')
                    })
                    console.warn("datar2",data)

            
                    
        }, [currentPage])
        useEffect(() => {
      
            console.log("data changed use effect",data)
                    
        }, [data])


      

      return (
        <div>Listing
          {
            
          }
          {
            //here is not update

            
      data.lenght>1 ? <div>finito2</div> : <div>loading2</div>
      
    }

    {
    //here is working well
    loading==true?<div>loading</div>:<div>not loading</div>}
    {
      
    }
          <ArticleContainer data={data} loading={loading} />
          
      

      
      <Pagination nPages={currentPage} lastPage={lastPage} currentPage={currentPage} setCurrentPage={setCurrentPage} />

        </div>
      )
    }

Solution

  • You have a typo, lenght should be length. Can this be the issue?