Suman
Suman

Reputation: 359

I am not able to see card datas

I am getting the data from backend & I am able to see the data in console using console.log(this.state.products). But I am not able see datas in my cards and delete function is calling automatically. If possible I want to show the cards in grid and options with calling different functions like edit option will call edit(id) method and delete will call delete method. Imports are there. Here is my Products.js file content.

    const styles = theme => ({
        root: {
          flexGrow: 1,
        },
        paper: {
          padding: theme.spacing.unit * 2,
          textAlign: 'center',
          color: theme.palette.text.secondary,
        },
        card: {
            maxWidth: 400,
          },
          media: {
            height: 0,
            paddingTop: '56.25%', // 16:9
          },
          actions: {
            display: 'flex',
          },
      });

      const ITEM_HEIGHT = 40;

    class Products extends Component {


        constructor() {
            super();
            this.state = {
                products: [],
                searchString: ''
            };
            this.getProducts()
        }
        state = {
            anchorEl: null,
          };

          handleClick = event => {
            this.setState({ anchorEl: event.currentTarget });
          };

          handleClose = () => {
            this.setState({ anchorEl: null });
          };


         delete(id) {
            alert(id)
            axios.post('http://localhost:9022/test/products/delete/'+id)
              .then(res => {
                let updatedProducts = [...this.state.products].filter(i => i.id !== id);
                this.setState({products: updatedProducts});
              });
          }

        getProducts() {
            axios.get('http://localhost:9022/products/getAll')
                .then(res => {
                    this.setState({ products: res.data });
                    console.log(this.state.products);
                });
        }

        onSearchInputChange = (event) => {
            if (event.target.value) {
                this.setState({searchString: event.target.value})
            } else {
                this.setState({searchString: ''})
            }
            this.getProducts()
        }

        render() {
            const { anchorEl } = this.state;
        const open = Boolean(anchorEl);
            const { classes } = this.props;
            return (
                <div>
                    {this.state.products ? (
                        <div>
                            <TextField style={{ padding: 24 }}
                                id="searchInput"
                                placeholder="Search for products"
                                margin="normal"
                                onChange={this.onSearchInputChange} />
                            {this.state.products.map(currentProduct => (
                                <Card>
                                <CardHeader
                                  action={
                                    <IconButton aria-label="More"
                                    aria-owns={open ? 'long-menu' : null}
                                    aria-haspopup="true"
                                    onClick={this.handleClick}>
                                      <MoreVertIcon />
                                      <Menu
                                  id="long-menu"
                                  anchorEl={anchorEl}
                                  open={open}
                                  onClose={this.handleClose}
                                  PaperProps={{
                                    style: {
                                      maxHeight: ITEM_HEIGHT * 4.5,
                                      width: 100,
                                    },
                                  }}
                                >
                                     <option onClick={this.edit}>Edit</option>
                                     <option onClick={this.delete(this.state.products.id)}>Delete</option>

                                </Menu>
                                    </IconButton>
                                  }
                                  title= {this.state.products.title}
                                />

                                <CardContent>
                                  <Typography component="p">
                                   {this.state.products.id}
                                  </Typography>
                                </CardContent>
                              </Card>
                            ))}
                        </div>
                    ) : "No products found"}
                </div>
            )
        }
    }

    export default  withStyles(styles)(Products);

Upvotes: 1

Views: 54

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

To fix auto call of edit and delete function

Change

 <option onClick={this.edit}>Edit</option>
 <option onClick={this.delete(this.state.products.id)}>Delete</option>

To

 edit = (id) => {
   consoe.log(id);you will get id here
 }

 delete = id => {
        alert(id)
        axios.post('http://localhost:9022/test/products/delete/'+id)
          .then(res => {
            let updatedProducts = [...this.state.products].filter(i => i.id !== id);
            this.setState({products: updatedProducts});
          });
      }
 <option onClick={() => this.edit(currentProduct.id)}>Edit</option>
 <option onClick={() => this.delete(currentProduct.id)}>Delete</option>

In cards below is the corrected code. To access title and id you need to call currentProduct.id and currentProduct.title but not this.state.products.id

Also never forget to add key to Card element like I did below

render(){  
const productsArray = [];
  this.state.products.forEach((currentProduct, index) => {
    if((index+1) % 4 == 0){
      productsArray.push(<div className="row" key={currentProduct.id}>
          <Card>
          <CardHeader action={<IconButton aria-label="More" aria-owns={open ? 'long-menu' : null} aria-haspopup="true" onClick={this.handleClick}>
            <MoreVertIcon />
            <Menu
              id="long-menu"
              anchorEl={anchorEl}
              open={open}
              onClose={this.handleClose}
              PaperProps={{
                style: {
                  maxHeight: ITEM_HEIGHT * 4.5,
                  width: 100,
                },
              }}
            >
               <option onClick={() => this.edit(currentProduct.id)}>Edit</option>
               <option onClick={() => this.delete(currentProduct.id)}>Delete</option>
          </Menu>
          </IconButton>
            }
            title= {currentProduct.title}
          />

          <CardContent>
            <Typography component="p">
             {currentProduct.id}
            </Typography>
          </CardContent>
        </Card>
      </div>)
}else{
  productsArray.push(
    <Card key={currentProduct.id}>
          <CardHeader action={<IconButton aria-label="More" aria-owns={open ? 'long-menu' : null} aria-haspopup="true" onClick={this.handleClick}>
            <MoreVertIcon />
            <Menu
              id="long-menu"
              anchorEl={anchorEl}
              open={open}
              onClose={this.handleClose}
              PaperProps={{
                style: {
                  maxHeight: ITEM_HEIGHT * 4.5,
                  width: 100,
                },
              }}
            >
               <option onClick={() => this.edit(currentProduct.id)}>Edit</option>
               <option onClick={() => this.delete(currentProduct.id)}>Delete</option>
          </Menu>
          </IconButton>
            }
            title= {currentProduct.title}
          />

          <CardContent>
            <Typography component="p">
             {currentProduct.id}
            </Typography>
          </CardContent>
        </Card>
  )
}
       })

  return(
    <div>
      <TextField style={{ padding: 24 }}
          id="searchInput"
          placeholder="Search for products"
          margin="normal"
          onChange={this.onSearchInputChange} />
      {productsArray.length > 0 ? {productsArray} : "No products found"}
    </div>
  )
}

Upvotes: 2

Related Questions