0

I have an array that looks like this.

[{"id":19,"name":"asd","salary":123},{"id":20,"name":"wer","salary":1}]

But when I try to map through it in React I get an Error

Uncaught TypeError: data.map is not a function

import React, { Component, useState, useEffect } from 'react';

function EmployeeList() {
const [data, setData] = useState({ items : [] });

const getEmployees = () => {
    fetch("http://127.0.0.1:8000/api/employee-list")
    .then((response) => response.json())
    .then((data) => {
        setData(data);
        console.log(data);
    })
};

useEffect(() => {
    getEmployees();
}, [])

return (
    <div>
        <ul>
            {data.map((employee) =>
                <li>{employee.name}</li>
            )}
        </ul>
    </div>
)
export default EmployeeList;

1 Answer 1

2

That's because you are not setting data to an array, but an object at first. Use this instead:

const [data, setData] = useState([]);

This assumes that your data comes back from the API as you specified, i.e., as an array. If instead it comes back in the format suggested by your original initial value then you'd need to use:

   {data && data.items && data.items.map((employee) =>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.