import React, { useState, useEffect } from 'react';
import axios from 'axios';
{const CustomerList = () => {
const [information, setInformation] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (isLoading) {
axios.get('').then((response) => {
setInformation((prevInfo) => {
return [...prevInfo, response.data];
});
});
}
return () => {
setIsLoading(false);
};
}, [information, isLoading]);
return (
<>
<h2>Name: </h2>
{information.map((item, index) => (
<div>
<div>{item[index].customer.firstName}</div>
<div>{item[index].customer.lastName}</div>
</div>
))}
</>
);
};
export default CustomerList;
Any way to get around this? Thanks!
That's not how map works. With these arguments to the callback:
information.map((item, index) => ...
index is the current index when iterating over the information array, and item is the element at that index. It's not another copy of the entire array. So instead of this:
item[index].customer.firstName
You would just do this:
item.customer.firstName
As an aside, when iterating over an array to output a list in React you would want to add a key to the top-level element. You can use index for this purpose if you like:
{information.map((item, index) => (
<div key={index}>
...
</div>
))}
Or if item has a unique identifier then you can use that instead and remove index entirely.
item[index] is not correct, since item refers to the element of the array at that index anyway.
const data = [1,2,3,4,5,6,7,8,9,10]
const mappedData = data.map((d, index) => {
console.log("index is", index)
console.log("d is", d)
console.log("-----------------------------")
return d
})
const data = [1,2,3,4,5,6,7,8,9,10]
const mappedData = data.map((d, index) => {
console.log("index is", index)
console.log("d[index] is", d[index]) //undefined since d is not an array
console.log("------------------------------")
return d
})
When you map() an array of items, you are handling each item separately, therefore you don't need the index, you could use the index as key, read more about lists and keys here.
{information.map((item, i) => (
<div key={i}>
<div>{item.customer.firstName}</div>
<div>{item.customer.lastName}</div>
</div>
))}