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

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...

The customized MUI IconButton is not compatible with tooltips

My IconButton has been styled to meet my requirements, but I am encountering an issue with the ToolTip placement. Currently, instead of appearing near the button, it shows up in the top left corner of the page. What could be causing this problem? import { ...

Is it possible to use bootstrap to hide specific components depending on the size of the media screen?

Struggling with styling responsiveness and hoping to find a Bootstrap class that can easily hide components on medium and small screens. I'm looking for a way to hide headings, paragraphs, buttons, and more without any extra hassle. ...

Testing a component in Angular 2 that utilizes the router-outlet functionality

I recently set up an angular 2 project using angular-cli. As part of the setup, I created a separate AppRoutingModule that exports RouterModule and added it to the imports array in AppModule. Additionally, I have the appComponent which was generated by an ...

"Implementing classes with AngularJS: A Step-by-Step Guide

Is there a way to dynamically add a class to the i tag after a button is clicked in AngularJS? <button type="button" title="Like" ng-click="countLikes(product.title)" class="btn btn-compare"> <i class="fa fa-thumbs-o-up"></i> </ ...

Obtaining two divisions that simultaneously display partials in a parallel manner

It's proving difficult to align two divs containing rendered partials side by side within a form. Strangely enough, when I replace the divs with plain text, they respond perfectly to my style changes. However, as soon as I include the render code, the ...

Introduction to the CodeIgniter wkhtmltopdf library

Seeking assistance here - I am attempting to generate a printable pdf report for a calendar using Codeigniter and the fullcalendar jquery library. I have previously used mpdf successfully for creating pdf reports, but when applied to my calendar page, it ...

Guide on transforming BinData into an Image and showcasing it on a React front end

I need to display images on the React front end that are currently in BinData format from MongoDB. The response object and data look like this. I tried passing the binary data in the src attribute of the img element with the mimetype and data encoding type ...

Guide to including objects into your project without the need for babel through the use of CDN

I'm struggling with getting my Vue code to transpile properly due to some issues. I have resorted to loading Vue and other packages directly using CDN links, like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-vue/1.8.33/surv ...

Could you explain the distinction between Node.bind() and Template Binding?

Currently, I am exploring the documentation for Google Polymer and have come across two types of data binding - Node.bind() and Template Binding. Can someone please explain the distinction between Node.bind() and Template Binding to me? ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

Revise website design to adjust dynamically according to screen dimensions

Currently, I am working on a school project with a website created by former students. Unfortunately, I have limited knowledge of HTML and CSS which has made it challenging for me to ensure the site is mobile-friendly. There are issues such as text overflo ...

How to make the parent div adjust its height to fit the children [CSS]

I am facing an issue with my parent div's height when adding more children. Despite setting the height of the parent to auto or not specifying a height at all, it ends up with a random height that does not seem to match the sum of its children. Even i ...

Identify all paths with or without the .html suffix, excluding static resources

I am working on configuring a universal handler for requests that do not pertain to images or favicons. I want this handler to manage paths like /index, /index.html, /user/123, and similar, while excluding /favicon.ico, /sunflower.png, /images/starfish.png ...

Using Vue 3's emit in place of v-model

I am facing a challenge with integrating a custom dropdown select component. The idea is to use v-model to retrieve data from the parent component, but I am unsure how to pass that through an emit. Can anyone clarify this for me? Here is my parent compone ...

Is it necessary to insert a thread sleep in HtmlUnit before clicking a button?

I have been experimenting with HtmlUnit to extract scores from the BBC Sports website Upon loading the page, it initially displays Premier League scores. To view scores for other leagues, one must use a dropdown menu and click the 'Update' butto ...

Having trouble with Route Param in React after deploying the application to an Apache server

I am facing an issue with my React app that uses react-router. I have included router params in my Routes, and while it works fine locally, the link with route params is not working once deployed on an Apache server. Can someone assist me in resolving this ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Angular JS encountered an issue with executing 'removeChild' on 'Node' for HTMLScriptElement.callback, leading to an uncaught DOMException

I am currently using Angular's JSON HTTP call. When making a post request, I experience an error during runtime: Uncaught TypeError: Cannot read property 'parentElement' of undefined at checklistFunc (masterlowerlibs.67785a6….js:42972 ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...