简体   繁体   中英

Trouble displaying the data from an api

So, this a weird problem. Yesterday everything was working fine, I could see the category object displayed, I could switch between categories, but today I wanted to continue the project, but the data is not being displayed, I can not even see the object in the console. What could be the problem, is it in the Fetch I would really really appreciate the help

import React, {useState, useEffect} from 'react'
import URL from '../utilis/URL'
const BookContext = React.createContext();
export default function BooksProvider({ children }) {
  
  const [data, setData] = useState([])
  const [currentSelectedCategory, setCurrentSelectedCategory] = useState([]);

  const handleSelectCategory = (category) => {
    setCurrentSelectedCategory(data[category]);
  };

  const fetchData = async () => {
    const response = await fetch(URL);
    const result = await response.json();  
    console.log(data.result)
    setCurrentSelectedCategory(result[Object.keys(result)[0]]);
    setData(data);
  };

  useEffect(()=>{
    fetchData();
  },[])
return (
    <BookContext.Provider value={{ data, handleSelectCategory, setCurrentSelectedCategory, currentSelectedCategory }}>
      {children}
    </BookContext.Provider>
  );
}
export {BookContext, BooksProvider}

import React,{useState, useEffect} from 'react'
import './Home.css'
import Books from './Books'
import { BookContext } from "../../context/books";
const Home = () => {
   const {data, handleSelectCategory, currentSelectedCategory } =React.useContext(BookContext)
    return (
        <div className='books__container' >
          <h1 className='categories'>Categories</h1>
            {Object.keys(data).map((key, index)=>{
            let books = data[key];
            return (
              <> 
              <span key={key} onClick={() => handleSelectCategory(key)} className='books__list' >
              {books[0].category}
              </span>         
             </>
              );})}
              <Books category={currentSelectedCategory} />
        </div>
    )
}

export default Home

This doesn't do anything:

console.log(data.result)

Because data is an empty array (and arrays have no result property anyway):

const [data, setData] = useState([])

And this doesn't do anything:

setData(data);

Because you're just updating the state to itself , which changes nothing and probably doesn't trigger any re-render. (Though even if it does, the render is mapping the elements of data which is still an empty array.)

You probably meant to set the data state object to the result from the API?:

setData(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM