Home > Software engineering >  Conditionally Rendering of Component
Conditionally Rendering of Component

Time:08-17

I am simulating an async event using setimeout, so after 3sec it pushes a value to the data array.

I am then checking the array length to conditionally render components, but the Loading component does not change even after isEmpty is false. It keeps showing Loading...., which is the first render.

Here is the full code below

import { useState, useEffect } from 'react';

export default function App() {
  const [isEmpty, setisEmpty] = useState(true);
  const data = [];
  
useEffect(() => {
  setTimeout(() => {
    data.push('newvalue');
    console.log(data);
    console.log('Array Length: ', data.length);
  }, 
    3000);
    console.log('Array Length: ', data.length);
    if(data.length > 0){
      setisEmpty(false);
    }else{
      setisEmpty(true);
    }
}, [])

    return (
     <>
     {isEmpty ? <h1>Loading...</h1> : <h1>Data Available</h1>}
     </>
  );
}

CodePudding user response:

Try making data a state and then use a useEffect to update the empty flag.


import { useState, useEffect } from "react";

export default function App() {
  const [isEmpty, setisEmpty] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
    setTimeout(() => {
      const temp = [...data];
      setData([temp, "newvalue"]);
      console.log(data);
      console.log("Array Length: ", data.length);
    }, 3000);
  }, []);

  useEffect(() => {
    console.log("Array Length: ", data.length);
    if (data.length > 0) {
      setisEmpty(false);
    } else {
      setisEmpty(true);
    }
  }, [data]);

  return <>{isEmpty ? <h1>Loading...</h1> : <h1>Data Available</h1>}</>;
}


CodePudding user response:

There is an extra { inside your map function, may be this is causing the problem.

  • Related