'Why do I get undefined when mapping and passing through a prop (ReactJS)
I can get the data out correctly and see it in the console as I want it to display but mapping and getting it through is the issue I seem to fail on..

This is my code
import React, {useState, useEffect} from 'react'
import axios from 'axios';
import server from '../backend/server.jsx';
import Home from './Home';
function ListImage() {
const [api, setApi] = useState('');
const getAllData = () => {
axios
.get(`${server}/images`)
.then((response) => {
console.log(response.data);
setApi(response.data);
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
getAllData();
},[]);
return (
<>
{api ?
api.map((item) => {
console.log(item);
return <Home data={item.data} />;
}): <p>Not found</p>}
</>
)
}
export default ListImage
And then passing to this where i only get undefined in console
import React from 'react'
function Home({ data }) {
console.log(data)
return (
<>
<p>{data}</p>
</>
)
}
export default Home
Solution 1:[1]
Try with this. I think your map function gets called when the initial render. Make sure the response. data should return an array.
ps: You render your home component in an array. That's wrong. Pass the data to the component and map your array on the home component.
import React, {useState, useEffect} from 'react'
import axios from 'axios';
import server from '../backend/server.jsx';
import Home from './Home';
function ListImage() {
const [data, setData] = useState(null);
const getAllData = () => {
axios
.get(`${server}/images`)
.then((response) => {
console.log(response.data);
setData(response.data);
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
getAllData();
},[]);
return (
<>
{api ? <Home data={data} /> : <p>Loading...</p>}
</>
)
}
export default ListImage
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stoXmod |
