Damian Kursa
Damian Kursa

Reputation: 45

Map through JSON data from API return undefinded

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 :

enter image description here

Could someone help me point out what I am doing wrong here?

Thank you in advance!

Upvotes: 0

Views: 54

Answers (2)

Shri Hari L
Shri Hari L

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

Ron
Ron

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

Related Questions