2

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.

br0526
  • 69
  • 1
  • 8
  • And what does `UseData` do? – tdranv Jul 18 '20 at 07:15
  • useData call other hook to access the constant JSON endpoint and stores the response. It also contains the formatted response data by destructuring arrays to be used as a object by other components via props – br0526 Jul 18 '20 at 07:46
  • So you have `setData()` and `UseData()`? Can you add `UseData()` to the question? – tdranv Jul 18 '20 at 07:48
  • UseData hook return the above attached array. – br0526 Jul 18 '20 at 07:58
  • It is not clear to me what you are trying to achieve. Perhaps rework the example given and the explanation. One thing that I'm pretty certain on is that you would want to use the `useEffect()` hook. – tdranv Jul 18 '20 at 08:08
  • 1
    You can not call `UseData` hook conditionally like this `!data &&UseData(...)`, it breaks rules of hooks: https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level – Tony Nguyen Jul 18 '20 at 08:15

1 Answers1

1

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}
        </>
    )
}
 
Mateen
  • 1,455
  • 10
  • 17
  • Thanks so much for the solution, it works.. :) meanwhile looked into it https://blog.logrocket.com/a-guide-to-usestate-in-react-ecb9952e406c/ – br0526 Jul 18 '20 at 08:40
  • https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect#:~:text=11%20Answers&text=Passing%20an%20empty%20array%20as,thus%20stopping%20any%20infinite%20loops. – br0526 Jul 18 '20 at 15:01
  • https://stackoverflow.com/questions/53574614/multiple-calls-to-state-updater-from-usestate-in-component-causes-multiple-re-re – br0526 Jul 18 '20 at 16:49
  • When I added useState([]), I can get the array, but it forms the infinite loop though I pass array.length or empty array at the end of the hook, UseData(formattedData => { console.log(recentData) //// recentData has response setData(recentData); } },[ ]) How to fix infinite loop here.I followed most ways to fix but unlucky. – br0526 Jul 18 '20 at 21:55
  • Can you reproduce the problems in Codesandbox? without knowing what hooks and how you're using it, it's impossible to say where the problem lies. – Mateen Jul 18 '20 at 23:06
  • 1
    Maybe you're using `useEffect` hook in some places and you've some deps in the deps array that you're changing inside the hook which is causing the infinite loop. – Mateen Jul 19 '20 at 12:22