Trigger a series of functions upon clicking with ReactJS

Need some assistance with an alert message functionality. I have a button labeled Checkout, and when clicked, it should clear the cart and display an alert. At present, the individual functions work as expected - calling emptyCart() works fine, and calling notify() with just toast("Wow so easy!") also works smoothly. However, when both functions are called together, only the emptyCart() function seems to execute successfully because it removes all items, including the button itself. As a result, the toast("Wow so easy!") does not get displayed since the button is no longer there. I'm looking to resolve this issue by displaying the alert message and clearing all items from the wishlist. Any help would be greatly appreciated.

Sharing my current code below:

import React, { useEffect } from 'react';
import { Button, Container, Col, Row, Table } from 'react-bootstrap';
import { useCart } from 'react-use-cart';
import { useThemeHook } from '../GlobalComponents/ThemeProvider';
// Additional imports...

const Cart = () => {
    // Component logic...
};

export default Cart;

Answer №1

It's a good idea to consider placing the <ToastContainer> element outside of the !isEmpty conditional render block, like this:

{!isEmpty &&
  <Row
    style={{ bottom: 0 }}
    className={`${theme ? 'bg-dark text-white' : 'bg-light text-dark'} justify-content-center w-100`}
  >
    <Col className="py-2">
      <h4>Total Price: $ {cartTotal}</h4>
    </Col>
    <Col className="p-0" md={4}>
      <Button variant="danger"
          className="m-2"
          onClick={() => emptyCart()}
      >
        <BsCartX size="1.7rem" />
        Clear Cart
      </Button>
      <Button
        onClick={()=>{ notify(); }} 
        variant="success"
        className="m-2"
      >
        <BsCartCheck size="1.7rem" />
        Checkout
      </Button>
    </Col>
  </Row>
}
<ToastContainer />

Alternatively, you can also place the <ToastContianer> in another location when isEmpty is true:

{!isEmpty &&
  <Row
    style={{ bottom: 0 }}
    className={`${theme ? 'bg-dark text-white' : 'bg-light text-dark'} justify-content-center w-100`}
  >
    <Col className="py-2">
      <h4>Total Price: $ {cartTotal}</h4>
    </Col>
    <Col className="p-0" md={4}>
      <Button variant="danger"
          className="m-2"
          onClick={() => emptyCart()}
      >
        <BsCartX size="1.7rem" />
        Clear Cart
      </Button>
      <Button
        onClick={()=>{ notify(); }} 
        variant="success"
        className="m-2"
      >
        <BsCartCheck size="1.7rem" />
        Checkout
      </Button>
      <ToastContainer />
    </Col>
  </Row>
}
{isEmpty && <ToastContainer />}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

Applying a custom theme to your entire application is a simple process that can

After following the guidelines provided by the Material docs, I have customized a theme for my React application. Despite implementing the changes in my index.js, I am facing difficulties in getting components like NavBar and AppBar to reflect these modi ...

Showcase each video stored within a specific directory in the form of a list using HTML 5

I'm working on an application that requires me to showcase a series of videos on a single HTML5 page using the video tag. Despite successfully uploading files to my folder, I am struggling to display them properly. My search for a solution has been fr ...

Creating an alarm clock with customizable time and date formats using ReactJS with Material-UI integration

Here is the code I have written: const date = new Date(); const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`; return ( <Box> < ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Position the button at the corner of the textarea

How can I position two buttons below a text_area, aligned with the bottom right corner of the text area? Here is what I have tried so far: Current code snippet: form with modal <%= form_for @note, :url => registrant_notes_path(@registrant), remote: ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...

Dragging items in the horizontal list of Knockout-Sortable causes them to be pushed vertically

For my application development using knockout.js, I am implementing knockout-sortable to create drag-and-drop sortable lists. The setup involves a vertical list with each item containing a horizontal list. While the vertical lists are functioning properly, ...

Is it possible to have dual images as the background for an HTML div?

Is it possible to use two images for a DIV background in CSS? I have one image that is just the background color and another that is a logo. Here's the code snippet I am currently using: .header{ background-attachment: scroll; background-clip ...

"Title, background hue 3, and color lined up in a single

.title { background-color: #FFC20E; font-size: 23px; font-weight: 600; padding: 5px 0px 5px 22px; font-family: "Open Sans"; } <h3 class="title">Title</h3> I need to create a title with a unique background color, can you ple ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...

Using jQuery's .html() method will remove the selected attribute from the dropdown menu option

When generating HTML dynamically, a select element is included. After choosing an option inside it, everything works fine. For example: <div id="test"> <select> <option value="1">1</option> <option value="2" selec ...

generate a dropdown menu within a CSV file using JavaScript

Currently, I am working on exporting a CSV file in Reactjs and facing an issue with creating a dropdown in the generated CSV file. I have attempted using plugins like excel.js, shell.js, as well as csvlink download. <CSVLink data={data}>Download me ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

Tips for inserting an AJAX response into the corresponding list item:

When the page loads, I am attempting to send an ajax request that will fetch data for each li element by extracting the href link inside them using the jQuery each() method to generate a dynamic URL for the ajax request. Although I am able to retrieve dat ...

I believe I am attempting to add some space to a row using CSS, or at least that's what I think I'm trying to achieve

Hey there, I need some help with adding an icon "services" section to my website. CSS is not my strongest suit, so I'm reaching out for assistance. My goal is to create blocks for the icons that don't touch the edge of the page and have a margin ...

Issue with mix-blend-mode causing text to not show up on top of the gradient

I am struggling to find a way to make text easily readable over my gradient background. Despite trying to use MUI's Typography or a simple <p>, the contrast isn't great as the text appears in black. After some research, I discovered that I ...

The framework of AngularJS modules

As I delve into structuring multiple modules for our company's application, I find myself at a crossroads trying to design the most optimal architecture. Research suggests two prevalent approaches - one module per page or a holistic 'master' ...

React not showing multiple polylines on the screen

I'm currently working on an application aimed at practicing drawing Kanji characters. To draw the lines, I'm utilizing svg. The issue I've encountered is that when I try to draw multiple separate lines using a 2D array of points for each lin ...

How to effectively compare time duration with a timer in the Laravel framework

I am managing a table that stores various job entries for employees. Each job entry includes a column for duration. I would like to trigger an alert or other event when the duration of a job has ended. My project is built using Laravel and VueJS. Below i ...