search

Home  >  Q&A  >  body text

Method .map doesn't work in application React

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粉495955986P粉495955986239 days ago383

reply all(1)I'll reply

  • P粉127901279

    P粉1279012792024-04-03 12:07:48

    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>
          )}
        </>
      );
    };

    reply
    0
  • Cancelreply