Francislainy Campos
Francislainy Campos

Reputation: 4164

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'm trying to use for each to loop through it but it won't let me.

Basically, I want to avoid having this sort of hardcoding here 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.

Upvotes: 0

Views: 1212

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370769

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)

Upvotes: 1

Related Questions