V
V
Vadim Semennikov2019-06-19 13:11:15
JavaScript
Vadim Semennikov, 2019-06-19 13:11:15

React how to remove a product?

Hello!
I load products from JSON and display them. Here is the code:

import React, {Component} from 'react';
import GetJson from '../../service/service-class';


export default class Product extends Component {
    getProductsList = new GetJson();
    state = {
        productsList: []
    };

    componentDidMount() {
        this.getProductsList
            .getProducts()
            .then((productsList) => {
                this.setState({
                    productsList
                })
            })
    };

    items(arr) {

        return arr.map((product) => {
            return (
                <div key={product.id} className="col-md-3">


                    <div className="card">
                        <img src={product.url} className="card-img-top" alt="{product.name}"/>
                        <div className="card-body">
                            <h5 className="card-title">{product.name}</h5>
                            <p className="card-text">{product.description}</p>
                            <div className="price">Price: <span>{product.price}</span>$</div>
                        </div>
                        <button className="btn btn-danger" onClick={() => this.props.onDelete()}>X</button>
                    </div>


                </div>
            )
        })
    }

    render() {

        const {productsList} = this.state;
        console.log(productsList);
        if (!productsList) {
            console.log('null');
        }
        const items = this.items(productsList);
        return (
            <div className="row">
                {items}
            </div>
        )
    }
}

Please tell me how to delete items one by one and all together.
By the way console.log(productsList); is displayed twice and NULL the first time. why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-19
@VadimRosh

Please tell me how to delete items one by one and all together.

If there is no API on the back and you are loading data from a json file, then nothing.
Because componentDidMount fires after render is called. This is fine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question