Estoy usando React y el componente Home me devuelve un error que dice latestNews.slice is not a function
en mi caso latestNews es un array el problema surgio cuando reemplace const latestNews = api.latest();
por un condicional const latestNews = (await this.props.query) ? api.busqueda() : api.latest();
este es el jsx del home.
import React, { Component } from "react";
import Grid from "@material-ui/core/Grid";
import Skeleton from "react-loading-skeleton";
import Card from "../components/Card";
import api from "../utils/api";
import "./_home.scss";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
latestNews: [],
searchQuery: ""
};
}
async componentDidMount() {
this.setState({ isLoading: true });
const latestNews = (await this.props.query) ? api.busqueda() : api.latest();
// this.props.query prop a home
//const latestNews = api.latest();
this.setState({ latestNews: latestNews.slice(0, 10), isLoading: false });
}
render() {
const { isLoading, latestNews } = this.state;
return (
<div>
<Grid
container
spacing={3}
align="center"
style={{ marginTop: "10px" }}
>
{isLoading &&
Array.from({ length: 10 }, (_, index) => (
<Grid item xs={12} lg={4} key={index}>
<Skeleton width={282} height={337} />
</Grid>
))}
{latestNews.length > 0 &&
latestNews.map(latestNew => (
<Grid item xs={12} lg={4} key={latestNew.news_id}>
<Card data={latestNew} />
</Grid>
))}
</Grid>
</div>
);
}
}
export default Home;
y esto es lo que tengo en api
import dayjs from "dayjs";
const BASE_URL = "--->aqui--va--la--API_URL";
const getActualDate = () => dayjs().format("YYYY[-]MM[-]DD");
const api = {
latest: async (date = getActualDate()) => {
try {
const response = await fetch(`${BASE_URL}/latest/${date}`);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
},
category: async (categoryId = "") => {
try {
const response = await fetch(`${BASE_URL}/news/category/${categoryId}`);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
},
busqueda: async (searchId = "") => {
try {
const response = await fetch(`${BASE_URL}/news/busqueda/${searchId}`);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
};
export default api;