Tarky Krocky
Tarky Krocky

Reputation: 41

Why this happens with React JS?

I am trying to fetch data using React JS and I am having the following error in my console:

Uncaught Error: Objects are not valid as a React child (found: object with keys {productsList}). If you meant to render a collection of children, use an array instead.

And here is my code:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

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

    //Lifecycle hook
    componentDidMount () {
        axios.get('/api/storageapp')
        .then(response => {
            console.log(response)
            this.setState({
                products: response.data,
            })
        })
    }
    render() {
        const { products } = this.state;
        const productsList = products.length ? (
            products.map(product => {
                return (
                    <div key={product.id}>
                        <div>{product.product_name}</div>
                    </div>
                )
            })
        ) : (
            <div>No products were found.</div>
        )

        return (
            {productsList}
        );
    }
}
export default Products;

if (document.getElementById('products')) {
    ReactDOM.render(<Products />, document.getElementById('products'));
}

Any clue what's happening?

Upvotes: 0

Views: 50

Answers (1)

Quentin
Quentin

Reputation: 943537

Because you're returning an object:

    return (
        {productsList}
    );

You should be returning just productsList. Get rid of the object literal syntax around it.

return productsList;

Upvotes: 2

Related Questions