I have written code in React JS that receives data from a backend. This backend connects to a database.
I receive this data using axios, but I get this error: "data.map is not a function ( **react.js – express.js – MongoDB **)".
I have a card component using props that calls only two data (name & image)
I receive them in the console and I have used **Cors **in the backend
npm i cors/ const cors = require(‘cors’) / app.use(cors())
Page Gallery
import {useState , useEffect} from 'react';
import axios from 'axios';
import CardSmall from '../Components/CardSmall';
const Gallery = () => {
const [ data , setData ] = useState([]);
useEffect(() => {
axios.get("http://localhost:5000/api/items/")
.then(res => {
console.log(res.data);
setData(res.data);
})
.catch(err => console.log(err));
}, []);
return (
<div className='w-100 vh-100'>
<h1>Gallery</h1>
<div style={{width:'90%', margin:'auto',display:'flex', flexWrap:'wrap', justifyContent:'center'}}>
{
data.map(item => <CardSmall key={item._id} {...item} />)
}
</div>
</div>
)
}
export default Gallery
Card component: I expected it to show the data one after the other in separate cards.
Before, I could display the data, but I created the data using a fake server (json-server).
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
function CardSmall({name , image}) {
return (
<Card style={{ width: '18rem' }} >
<Card.Img variant="top" src={image} alt={name} />
<Card.Body>
<Card.Title>{name}</Card.Title>
<Button variant="primary">Go somewhere</Button>
</Card.Body>
</Card>
);
}
export default CardSmall;
2
Answers
I was only able to get the information using fetch!!!!
}, []);
But I still don't understand why it was not accepted by axios
Since component gets rendered before useEffect, you are getting this error.
To overcome this have a condition on data