简体   繁体   中英

How to initiate React hook state with foreach loop

Apologies if this question may have been asked before, I'm not sure if that's the case. I come from a Java background and am super new to React and not very proficient on this framework yet. But what I'm trying to do is to retrieve all the data from an array to set it to another array initiated through useState. I'm not sure the syntax for that as I try to for each loop through it but it won't let me.

Basically, I want to avoid having this sort of hardcoding here please as my data is dynamic coming from an api:

 const [data, setData] = useState([

        {
            name: reports[0].title,
            runDate: reports[0].runDate,
            createdDate: reports[0].createdDate,
            category: reports[0].category.title,
            actions: 4, 
        },
        {
            name: reports[1].title,
            runDate: reports[1].runDate,
            createdDate: reports[1].createdDate,
            category: reports[1].category.title,
            actions: 4,
        },
    ]
)

Thank you very much.

It sounds like all you need is something that can iterate through the reports array and transform it:

// pass `reports` into this if you need to
const getInitialData = () => reports.map(report => ({
  name: report.title,
  runDate: report.runDate,
  createdDate: report.createdDate,
  category: report.category.title,
  actions: 4,
}));
const [data, setData] = useState(getInitialData);

(I'm passing a function to useState so you only have to transform the reports into the desired data structure on mount, rather than on every render)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM