Reputation: 45
Hello I am trying to map through data from API like this :
import React, { useEffect, useState } from "react"
import Layout from "../components/layout"
import { getAllActiveJobs } from "../../backend/controllers/apiHandler"
const ForAnsatte = () => {
const [activeJobs, setActiveJobs] = useState([])
const init = () => {
getAllActiveJobs().then((data) => {
setActiveJobs(data)
})
}
useEffect(() => {
init()
return () => {}
}, [])
return (
<Layout>
{activeJobs.data
? activeJobs.data.map((item) => {
return <div key={item.jobId}>{item.candidateId}</div>
})
: "Loading..."}
</Layout>
)
}
export default ForAnsatte
But then I get this error : TypeError: activeJobs.data.map is not a function
API return JSON object which looks like this :
Could someone help me point out what I am doing wrong here?
Thank you in advance!
Upvotes: 0
Views: 54
Reputation: 4894
data
is not an array. It is an object!
I think you should something like this,
Object.keys(activeJobs.data).forEach((e) => {
console.log(activeJobs.data[e])
})
and render it like this,
return ( <Layout> {
activeJobs.data ?
Object.keys(activeJobs.data).map((item) => {
return <div key = {
activeJobs.data[item].jobId
}> {
activeJobs.data[item].candidateId
} </div> }): "Loading..."
}
</Layout>
)
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Upvotes: 1
Reputation: 107
The data returned from the api seems to be a JSON object and map() works only for arrays.
I'd suggest looping through the JSON object using Object.keys(activeJobs.data).forEach()
Upvotes: 1