ReactJS: How to get response array inside State(useState) and check the length of the array when rendering/binding

Viewed 4171

ReactJS: How to get response array inside State(useState) and check the length of the array when rendering/binding. I dont know to set recentData array to the useState to get the length in the return.

import React, { useState } from "react";
import UseData from "../../hooks/useData";

const HomePage = (props) => {
  const [data, setData] = useState(false);
 
 !data &&
    UseData(formattedData => {
      const { hasError, recentData } = formattedData;
      console.log(recentData)  //// recentData has response 
      if (hasError) {
       //
      } else {
        setData(recentData); 
      }
    })
    
    return (
    // I want to get 'recentData' here like recentData.length > 0, have 'data' set true 
    {data && data.map((info, i) => (   
              <Grid key={i}>
                  member={info.firstName}
              </Grid>
            ))}
            
    // I want to get 'recentData' recentData.length === 1, 
    {data &&
              <Grid key={i}>
                  member={info.firstName}
              </Grid>
            ))}
    // I want to get 'recentData' recentData.length === 0
 
              <Grid >
                 No data to render
              </Grid>
        )
        }
        export default HomePage
recentData array returned from the useData hook

0:
{firstName: "XXXX"
lastName: "YYYY"}
1:
{firstName: "AAAA"
lastName: "BBBBB"}
2:
{firstName: "CCCC"
lastName: "DDDD"}

I dont know to set recentData array to the useState to get the length in the return.

1 Answers

You don't need to have extra work to get array length from the state. If the state you set, data, is an array, you simply access the length by using the property, .length anywhere, in JSX, you just need {} to use JavaScript code. Important, you have set the default data false, a boolean type, it will produce an error on initial render on accessing length, so put it to be empty array,

const [data, setData] = useState([]);

Let's see an example:

const myComp = () => {
    const [data, setData] = React.useState([]);
    // do some stuff here to fetch data from anywhere and set it to data
    return (
        <>
        {data.length === 0 ? <p>Length is 0</p>:null}
        {data.length === 1 ? <p>Length is 1</p>:null}
        {data.length > 1 ? <p>Length greater that 1</p>:null}
        </>
    )
}
 
Related