Rishiban R
Rishiban R

Reputation: 123

Uncaught type error: map function is not working for array variable

I am new to React. I have an array variable but when I call map function it doesn't work. I get "Uncaught (in promise) TypeError: this.state.products.map is not a function"

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            products: []
        };

componentDidMount() {
        fetch(url)
            .then((Response) => {
                this.setState({
                    products: Response.json()
                });
            })
            .catch(err => console.error);
    }
}

 render() {
        return (
            <div>
                <div className="col-lg-12">
                    {this.state.products.map(product1 => (
                        <Button key={product1.id} style={{ color: 'grey', radius: '5px', width: '90px' }}>
                            {product1.title}
                        </Button>
                    ))}
                    <br /><br /><br />
                </div>
            </div>
        );
    }
}
export default Category;

Where am I going wrong? Thank you.

Upvotes: 0

Views: 51

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Response.json() is a Promise. MDN. Assuming you are getting an array from the server you need

componentDidMount() {
        fetch(url)
            .then(res => res.json())
            .then((products) => {
                this.setState({
                    products
                });
            })
            .catch(console.error); // because err => console.error is a noop
    }
}

Upvotes: 2

Azamat Zorkanov
Azamat Zorkanov

Reputation: 819

I guess, when you're getting response the json response isn't array:

products: Response.json()

Could you please, check, if it actually array

Upvotes: 0

Related Questions