'TypeError: this.state.jokes.map

I want to show a joke from API.

I have this error: "TypeError: this.state.jokes.map is not a function"

My code:

import React, { Component } from "react";
import Footer from "../Footer/Footer";
import axios from "axios";
class Content extends Component {
    constructor(props) {
        super(props);
        this.state = {
            jokes: [],
        };
    }
    componentDidMount() {
        axios
            .get(`https://sv443.net/jokeapi/v2/joke/Programming?type=single`)
            .then((res) => {
                const jokes = res.data;
                this.setState({ jokes });
            });
    }
    render() {
        return (
            <div>
                <div className="content_containeer">
                    <h1>Full-stack .NET developer</h1>
                    {this.state.jokes.map((e) => (
                        <p>{e.joke}</p>
                    ))}
                    <Footer />
                </div>
            </div>
        );
    }
}

export default Content;

I am a newcomer in this and I want to understand why this error is caused.



Solution 1:[1]

This is the response from the url you fetch

https://sv443.net/jokeapi/v2/joke/Programming?type=single

{
    "error": false,
    "category": "Programming",
    "type": "single",
    "joke": "I have a joke about Stack Overflow, but you would say it's a duplicate.",
    "flags": {
        "nsfw": false,
        "religious": false,
        "political": false,
        "racist": false,
        "sexist": false,
        "explicit": false
    },
    "safe": true,
    "id": 301,
    "lang": "en"
}

It is not an array, it is an object. .map() only works on array.

You can try this one instead: https://v2.jokeapi.dev/joke/Any?amount=5&type=Single

fetch the res.data.jokes as your jokes state

example: https://codesandbox.io/s/charming-feather-sd2w8c

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1