7

Im trying to use fortnite api to display current item shop and i'm getting error likein the title, when I console log result it show an array but i cant map through it ? whY?

import React, { useState, useEffect } from 'react'
import axios from 'axios';
export default function itemShop() {
    const [shop, setShop] = useState('')
    const API = 'https://fortnite-public-api.theapinetwork.com/prod09/store/get?language={en}'
    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(
                API,
            );

            setShop(result.data);
        };
        fetchData();
    }, []);

    const { items } = shop;
    console.log(items)
    return (
        <div>
            <p>{shop.date}</p>
            {items.map(item => <p>{item.name}</p>)}
        </div>
    )
}

code sandbox : https://codesandbox.io/embed/km10wq4y5

0

5 Answers 5

17

You need to check items isn't null/undefined before rendering:

{items && items.map(item => (
        <p>{item.name}</p>
      ))}

Working: https://codesandbox.io/s/24vkqzn6xy

Sign up to request clarification or add additional context in comments.

Comments

5

Problem is in this line:

const [shop, setShop] = useState('')

Since you are expecting shop.items as an array, so define the initial state as:

const [shop, setShop] = useState({ items: [] });

Also assign unique key to each p, here:

<p key={item.itemid}>{item.name}</p>

Working Code.

Comments

4

You can also do it like this

{ items?.map(item => (<p>{ item.name }</p>)) }

Comments

1

For me I forget to add await in axios after calling async method. like the code below. Make sure to check your code again if above methods didn't help you.

async function getCategories() {
      try {
        const response = axios.get("API");
        setCategories(response.data);
      } catch (error) {
        console.log("error", error);
      }
    }

Comments

0

if anyone wants to understand this problem and its solution can visit the site web it was really helpful for me https://www.debuggr.io/react-map-of-undefined/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.