TypeError: resources.map is not a function

Issue

I am doing a mean stack app, and right now I am working on Home page. But i’m getting a error on UI. I checked chrome console data is fetching properly.

Parent Component

export default function Home() {

    const [resources, setResources]=useState('')

    useEffect(async () => {
       try {
            const res = await resource.getAll();
            setResources(res.data)
       } catch(err){
            console.log(err);
       }
    }, []);

    return (
        <Layout>
            <Resource resources={resources.slice(0,2)}></Resource>
        </Layout>
    )
}

Child Component

export default function Resource({resources}) {
    const dataRow = resources.map((value, index) => {
        return <div key={value._id}>
               { value.title }
        </div>
    })
    
    return (
        <section className="hero ">
            { dataRow }
        </section>
    )
}

Solution

Have you tried to init your State as an array instead of an empty string?

const [resources, setResources]=useState([])

Answered By – bernhard.wieland

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published