0

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;

1 respuesta 1

1

El error debe ser que para cuando se hace el setState la variable latestNews no es un array y por tanto no tiene definida una función slice, seguramente a ese punto tienes un objeto (promesa pendiente).

Te recomendaría cambiar un poco la lógica para que en la API recibas un flag (this.props.query) y dependiendo del valor retornes el fetch que aplique para que puedas usar algo así desde el componente.

api.metodo(this.props.query)
    .then(res => res.json())
    .then(res => {
        this.setState({ latestNews: res.slice(0, 10), isLoading: false });
    })
6
  • <code>async componentDidMount() { this.setState({ isLoading: true }); const latestSearch = api .busqueda(this.props.query) .then(res => res.json()) .then(res => { this.setState({ latestNews: res.slice(0, 10), isLoading: false }); }); const latestNews = (await this.props.query) ? latestSearch : api.latest(); // this.props.query prop a home //const latestNews = api.latest(); //this.setState({ latestNews: latestNews.slice(0, 10), isLoading: false }); }</code> el 7 nov. 2019 a las 20:02
  • me da otro error que dice Cannot read property 'json' of undefined que no puede leer el json el 7 nov. 2019 a las 20:03
  • tambien me dice que mi array no esta definido Cannot read property 'slice' of undefined el 7 nov. 2019 a las 20:06
  • Te dice Cannot read property 'json' porque si ya estas retornando el response.json() desde la API no es necesario ponerlo en el componente. el 8 nov. 2019 a las 12:22
  • 1
    Podrías actualizar tu API para ver el estado actual en el que lo tienes. pero supongo que es porque los metodos en la API los tienes definidos como async y tienes un try catch internamente. Cambialo de modo que tengas la función que retorna un fetch asi te aseguras que retorna una promesa que puedes enlazar en el componente con un then cuando esta se resuelva el 8 nov. 2019 a las 13:38

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.