I'm using Axios to retrieve data from the backend. When I log the data to the console, it appears as an object. However, I need the data to be in an array format. When I try to use the map function on the data, it gives me an error stating that data.map is not a function. I am using django in backend
function Search() {
const [data,setData] = useState([]) // setting data as array i had also used null here
useEffect(()=>{
axios.get("http://127.0.0.1:8000/api/listing") //using axios api
.then(response =>{
setData(response.data)
console.log(response.data) //data is appears as object when do console.log
})
.catch(error =>{
console.log("Error fetching data:",error)
});
},[]);
return (
<div>
<h1>Fetched Data</h1>
{/* <ul>
//data.map is not a function
{data.map(item =>(
<li key={item.id}>{item.title}</li>
))}
</ul> */}
</div>
)
}
export default Search
I have checked wheather data from backend is in form of array or object and i got that the data is not in form of array
if (Array.isArray(response.data)) {
setData(response.data);
} else {
console.error('Data is not an array:', response.data);
}
after that i tried to convert data to array in two ways
.then((response) => {
//if data is not in array convert it into array
const dataArray = Array.isArray(response.data) ? response.data : [response.data];
setData(dataArray);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
another way
<ul>
{[data].map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
but both way i got a warning
Each child in a list should have a unique "key" prop.
this error i get when i try to convert data to array
I got the problem solved here is my console.log output
I have an object that has a property called result which is an array therefore we have to do something like this we have to access the result array with the data object and then map over it to display the items
Here is how to do this