1

I am currently facing few problems when I am trying to render the API data to the browser.

problem 1:

Every time I tried to map through the data I got from API, I got an error saying:

fictions.map is not a function , I what is happening here , because fictions is an object.

problem 2: even i kinda solved problem 1 which I made it to an array, but every time i try to read the data property it return undefined .

this is how i access data properties

//let say A is an array of object i converted from the original data.
A.map(items=>{
console.log(items.title); // return undeined
})

Let me show you my code. I created an interface to define each data shapes

export default interface IBook {
  fictionId: string;
  title: string;
  author: string;
  descs: string;
  cover: string;
}

then create a class to fetch api

//get API by using axio
//API sources: LRY_API
import axios from "axios";
import IBook from "../interfaces/IBook";

class BooksApi {
  http = axios.create({
    baseURL: "https://api.pingcc.cn/fiction/search/fictionType",
  });
  async getFictions(name: string) {
    const response = await this.http.get<IBook[]>(`/${name}`);

    return response.data;
  }
}

export default new BooksApi();

in the App.js

import React, { useEffect, useState } from "react";
import Home from "./components/Home";
import Search from "./components/Search";
import "./App.css";
import Books from "./components/Books";
import BookApi from "./services/BookApi";
import IBook from "./interfaces/IBook";

function App() {
  const [fictions, setFictions] = useState<IBook[]>([]);

  let name: string = "love";

  const loadBooks = async () => {
    const api = await BookApi.getFictions(name);
    setFictions(api);
  };
  useEffect(() => {
    loadBooks();
  }, []);

  console.log(fictions);

  return (
    <div>
      <Home />
      <Search />
      {/* <Books items={fictions} /> */}
    </div>
  );
}

export default App;

API LINK: https://api.pingcc.cn/fiction/search/fictionType/爱情

I have been tring to solve this problem more then 2 days, please let me know if you need more detail to help me solve this problem.

0 Answers0