0

I am developing a react shopping cart app. If the user click on 'Clear Cart' button, the entire cart will be cleared. Before that the application should confirm the action and therefore, I used 'React Confirm Alert'. If the user click on 'Yes' button, it will clear the cart and it should navigate to the root page('/'). I searched over the internet and on the StackOverflow and tried the three ways given here. But nothing worked. For both this.props.history.push('/') and this.props.router.push('/') gives me a TypeError saying undefined object and for useHistory() it says violating react hooks principles. Is there anything I can do to make this work? Thanks in advance!

Code :-

import React, { useEffect, useState, Component} from 'react';

import Titles  from "../Titles";
import CartColumns from './CartColumns';
import EmptyCart  from "./EmptyCart";

import CartList from "./CartList";
import {connect} from "react-redux";
import {Link, Redirect} from "react-router-dom";
import Axios from "axios";
import { confirmAlert } from 'react-confirm-alert'; // Import
import 'react-confirm-alert/src/react-confirm-alert.css' // Import css

const mapStateToProps = ({ session, history}) => ({
    session, history
});

class Cart extends Component {

    constructor() {
        super();
        this.removeItem = this.removeItem.bind(this);
    }

    state = {
        Cart: [],
        total : 0,
        discount: 0
    };

    componentDidMount() {
        if(this.props.session.userId !== null){
            this.getItems();
        }
    }

    getItems = () => {
        //function to get the items
    };

    removeItem = (productId) => {
        //method to remove an item
    };

    clearCart = () => {

        confirmAlert({
            title: 'Clear Cart',
            message: 'Are you sure to clear the Cart?',
            buttons: [
                {
                    label: 'Yes',
                    onClick: () => {Axios.get('http://localhost:8000/api/cart/clearCart', {params:{userId: this.props.session.userId}}); 
                                    } //I want to redirect from here
                },
                {
                    label: 'No'
                }
            ]
        })
    };

    checkout= () => {
        //Checkout function
    };

    render() {
        let total = this.state.total;
        let discount = this.state.discount;

        if(this.props.session.username !== null){
            return (
                <section>
                    {(this.state.Cart.length > 0) ? (
                        <React.Fragment>
                            <Titles name ="Your " title = "Cart">Cart</Titles>
                            <CartColumns/>
                            <CartList cart = {this.state.Cart} removeItem={this.removeItem}/>
                            <div className="container">
                                <div className="row">
                                    <div className="col-10 mt-2 ml-sm-5 ml-md-auto col-sm-8 text-capitalize text-right">
                                        <h5>
                                            <span className="text-title">Sub Total: </span>
                                            <strong>$ {total}</strong>
                                        </h5>
                                        <h5>
                                            <span className="text-title">Discount: </span>
                                            <strong>$ {discount}</strong>
                                        </h5>
                                        <h5>
                                            <span className="text-title">Total: </span>
                                            <strong>$ {total - discount}</strong>
                                        </h5>


                                            <div className="col-10 mt-2 ml-sm-5 ml-md-auto col-sm-8 text-capitalize text-right">
                                                <button className="btn btn-outline-danger text-uppercase mb-3 px-5" type="button" onClick={this.clearCart}>Clear Cart</button>
                                                <button className="btn btn-outline-info ml-3 text-uppercase mb-3 px-5" type="button" onClick={this.checkout}>Check Out</button>
                                            </div>


                                    </div>
                                </div>
                            </div>
                        </React.Fragment>
                    ) : (
                        <EmptyCart/>
                        )
                    }
                </section>
            );
        } else {
            return(
                <Redirect to="/login" />
            );
        }

    }
}

export default connect(
    mapStateToProps
)(Cart);
  • Do you really store a `history` object in your redux state? Or did you mean to use the route props from a rendering `Route` via the `withRouter` HOC or directly from props? What and where is rendering `Cart`? – Drew Reese May 15 '20 at 03:04

2 Answers2

0

I think you have 2 options.

First: Just use window.location method like this

 // Simulate a mouse click:
window.location.href = "http://www.example.com";

// Simulate an HTTP redirect:
window.location.replace("http://www.example.com");

Second: Use react state

import React from 'react'
import { Redirect } from 'react-router-dom'
class Cart extends Component {

    constructor() {
        super();
    }

    state = {
      isRedirect: false 
    };
    const onClick = () =>{
     this.setState({isRedirect: true})
    }
   render() {
      let isRedirect = this.state.isRedirect;
      if(isRedirect == true){
       return <Redirect to='/target' />
     }
     return (
      <div>
        ... 
      </div>
     )
   )
 }
0
window.location.replace("http://localhost:3000/");

This statement will solve your problem. Happy Coding!