import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import '../styles/sales.css'; // Import the CSS file
function Sales() {
const [propertyData, setPropertyData] = useState([]);
useEffect(() => {
// Fetch data from your Django API using Axios
axios.get('http://127.0.0.1:8000/api/v1/core/for-sale/')
.then((response) => {
// Limit the photos to a maximum of four
const limitedData = response.data.slice(0, 4);
setPropertyData(limitedData);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
}, []);
return (
<div className="sales-container">
{propertyData.map((property) => (
<div key={property.id} className="property-card">
<Link to={`/property/${property.id}`}>
<img src={property.main_photo} alt={property.title} className="property-image" />
<h2 className="property-title">{property.title}</h2>
</Link>
<p className="property-description">{property.description}</p>
<p className="property-details">
{property.bedrooms} Bedrooms | ${property.price}
</p>
</div>
))}
</div>
);
}
export default Sales;
I was trying to fetch data from a django-rest api. I have installed the axios library, defined the CORS_ALLOWED_ORIGINS also added the corsheaders but the images cannot be rendered. I get the following error "Error fetching data: TypeError: response.data.slice is not a function"
2
Answers
Probably the response.data is coming in as null/undefined, how does a sample response look like? Can you post the result when you call
http://127.0.0.1:8000/api/v1/core/for-sale/
via Postman or the browsable API?If you’re using DRF viewsets the data will be returned like this:
If that’s the case you’d have to do
response.data.results.slice(0,4)
. Otherwise take a look at what the API actually returns and try working with that.