I'm passing an array (data) to the component via a prop, but then I can't map over data.
const Component1 = ({ data }) => {
console.log(data);
const renderData = () =>
data.map(singleItem => (
<OtherComponent key={singleItem ._id} singleItem ={singleItem} />
));
return (
<Row className="row--small-padding">{renderData()}</Row>
);
console.log(data)
returns array of objects as expected, however, the data is not being passed to another component. I assume is being rendered before the data is fetched?
My data fetching function looks like this:
const fetchAllData = async () => {
const response = await getData();
const data = await response;
setData(data);
};
useEffect(() => {
fetchAllData();
}, []);
I have worked this around by adding data &&
before the map function, but the data is being passed through many components and I would like to know if there is any other solution for this? How do I set my components to wait for data to be fetched and then render?
Edit: data array initial state is set to null, like this:
const Component= () => {
const [data, setData] = useState(null);
const fetchAllData = async () => {
const response = await getData();
const data = await response;
setSources(data);
};
useEffect(() => {
fetchAllData();
}, []);
return (
<>
<Component1 limit={4} data={data} />
<Component2 limit={4} data={data} />
<Component3 limit={4} data={data} />
</>
);
};
export default Component
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…