Map on props of ReactJS Redux

Viewed 33

I started my learning path few months ago (html, css, js) and I have a question for an issue that I have with react (just started learning it).

I have an error that says : data.map is not a function

I want to loop trough my array of objects with map, and dispatch the props (title, answer) to the child for each loop, to make a list of different FaqComponent having each the {title and answer}

    const data = useSelector(state => ({
        ...state.homePage.list
    }))
    console.log(data);

    return (
        <div>
            {data.map((title, answer) => (
                <FaqComponent
                    title={title}
                    answer={answer}
                />
            ))}
        </div>
    );
}

export default ...;

Thanks for your replies

2 Answers

You're using an object {} instead of an array [] syntax.

Try with:

 const data = useSelector(state => ([
        ...state.homePage.list
    ]));

You should declare "data"s type, if it is an array so your function should be like :

const data = useSelector(state => ([
    ...state.homePage.list
]))
    console.log(data);

    return (
        <div>
            {(data && data.length > 0) ? data.map((item, i) => (
                <FaqComponent
                    title={item.title}
                    answer={item.answer}
                    key={i}
                />)) 
                : <div>No Result!...</div>}
        </div>
    );
}

export default ...;
Related