user15134931
user15134931

Reputation:

map is not a function in react js

Tried to map down this response but it was showing me an error even when i put in in a usestate array. Kindly go through my code to see if you can fix the error..

function Comment() {
    const [comment_data, setcomment_data] = useState([]);
    useEffect(() => {
        const query = `
    query{
        forumAnswerId(id:1){
        forumAnswerBody
        forumAnswerTime
        forumAnswerCode1
        forumAnswerCode2
        forumAnswerCode3
        forumAnswerAuthor
        forumAnswerBoolean
        forumAnswerCode1Title
        forumAnswerCode2Title
        forumAnswerCode3Title
        }
        forumComment(forumAnswerComment:1){
                forumAnswerCommentPost
                forumAnswerCommentBody
                forumAnswerCommentAuthor
                forumAnswerCommentTime  
        }
        }
`;
        const opts = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query }),
        };
        const res = fetch('http://127.0.0.1:8000', opts)
            .then((res) => res.json())
            .then((r) => setcomment_data(r));
    }, [])
    const map = comment_data.map((e) => {
        return (
            <>
                {comment_data.map((inner) => (
                    <>
                        {inner.data?.forumAnswerId?.map((data) => (
                            <></>
                        ))}
                    </>
                ))}
            </>
        );
    });
    console.log(comment_data);
    return (
        <div>
            {map}
        </div>
    );
}

API structure

enter image description here

i have used a useEffect hook to load in data and store the data in the state variable and access it.

Upvotes: 1

Views: 515

Answers (2)

Rishav Maskey
Rishav Maskey

Reputation: 191

The comment_data that you've console.logged and shared shows that comment_data is an object that contains the key "data".

If you're looking to map all the keys for that object, you could do Object.keys(comment_data) and map that array and access values of keys like comment_data[key].

I think from the context of your code, you're looking for something like this:

const map = comment_data.data?.forumAnswerId?.map((data) => (<>{data.forumAnswerBody}</>))

Upvotes: 0

Oriun
Oriun

Reputation: 244

if I've well understood your api's reponse, what you're fetching is not an array. It's an object with a property data and that's what's in comment_data. So no comment_data.map()

Upvotes: 2

Related Questions