Method .map doesn't work in application React
P粉495955986
P粉495955986 2024-04-02 21:52:34
0
1
273

The .map method of the object does not work and I cannot interact with the object of the API I imported. On the browser's console I read the object.

This is a component razze("races")

const BASE_URL = "https://www.dnd5eapi.co/api/races";



const ListaRazze = () => {
  const [razze, setRazze] = useState<RazzeArray>();

  useEffect(() => {
    fetch(BASE_URL)
      .then((res) => res.json())
      .then((results) => {
        console.log('result', results);
        setRazze(results);

        const prova = Object.values(results);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }, []);

  return (
    
     <>
      {razze && razze.razze ? (
        razze.razze.map(({ indice, name, url }) => (
          <div key={indice}>{name} {url}</div>
        ))
      ) : (
        <div>Loading...</div>
      )}
    </>
  );
};

export default ListaRazze;

This is the interface in the package model

export interface RazzeArray {
    count: number
    razze: Razza[]
  }
  
  export interface Razza {
    indice: number
    name: string
    url: string
  }

Be able to enter the object

P粉495955986
P粉495955986

reply all(1)
P粉127901279

The data you receive is different than what you expected in the interface. Observe the properties of the api result and match the property names.

I also recommend that you keep your code in English for consistency and clarity.

export interface IRaceList {
  count: number
  results: IRace[]
}
  
export interface IRace {
  index: number
  name: string
  url: string
}

Set initial values ​​for your state. This will also make your code more predictable and consistent. If you don't want the initial state, make sure the type reflects this.

const RaceList = () => {
  const [raceList, setRaceList] = useState<IRaceList>({
    count: 0,
    results: []
  });

  useEffect(() => {
    fetch(BASE_URL)
      .then((res) => res.json())
      .then((results: IRaceList) => {
        setRaceList(results);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }, []);

  return (
     <>
      {raceList.count ? (
        raceList.results.map(({ index, name, url }) => (
          <div key={index}>{name} {url}</div>
        ))
      ) : (
        <div>Loading...</div>
      )}
    </>
  );
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!