0

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.

1
  • Please share the output of console.log(Response.json()) Commented Jul 20, 2018 at 11:52

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

products: Response.json()

Could you please, check, if it actually array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.