0

I am new to React and I am having a problem. How to iterate over an array in an array? When trying to iterate over an array using the map() method, an error occurs

my code:

import React, {useState, useEffect} from 'react';

import Header from '../modules/header/header';
import Footer from '../modules/footer/footer';

import './pages.scss';

function PageWorksItem({ match, location }) {

    const { params: { id } } = match;
    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [works, setItems] = useState([]);

    useEffect(() => {
        let cleanupFunction = false;
        fetch(`http://localhost:3001/works/${id}`)
            .then(res => res.json())
            .then(
                (result) => {
                    console.log(result);
                    setIsLoaded(true);
                    if(!cleanupFunction) setItems(result);
                },
                (error) => {
                    setIsLoaded(true);
                    setError(error);
                }
            )
            return () => cleanupFunction = true;
        }, [])

        if (error) {
            return <div className="works error">Error: {error.message}</div>;
        } else if (!isLoaded) {
            return <div className="works loading">. . .</div>;
        } else {
            return (
                <>
                    <Header />
                    <div className="works item">
                        {works.tags.map(item => (
                            <li>{item}</li>
                        ))}
                    </div>
                    <Footer />
                </>
            );
        }
    }

export default PageWorksItem;

JSON fragment:

{
    "works": [
        { 
            "id": 1, 
            "name": "21 one line SPA images",
            "cat": "Illustrations",
            "tags": ["one", "two", "free"]
        }
    ]
}

if you specify {works.tags} or with an index {works.tags[0]} - everything works, but if you iterate over the array, an error occurs.

6
  • Can you show result of console.log(result);? Commented Apr 29, 2021 at 14:16
  • PageWorksItem should return something! Commented Apr 29, 2021 at 14:17
  • @Viet { "id": 1, "name": "21 one line SPA images", "cat": "Illustrations", "tags": [ "one", "two", "free" ] } Commented Apr 29, 2021 at 14:21
  • your works state is object it should be array in order to use map function. Commented Apr 29, 2021 at 14:23
  • what if you do spreadOperator: setItems({...result})? Commented Apr 29, 2021 at 14:25

1 Answer 1

1

You are using works.tag.map. But the initialization value of works is an empty array []: const [works, setItems] = useState([]);. So works.tag is undefined and this error occurred. You can fix this issue by add optional chaining like this:

{works.tags?.map((item, index)=> (
   <li key={index}>{item}</li>
))}

Note: You need to add unique key in child componet when using map

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

1 Comment

That's correct. OP should rename works to work as the endpoint only ever returns a single work and not a list of works. Also it should not be initialised as an array but probably with null or a default work object.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.