Fatih mzm
Fatih mzm

Reputation: 395

show a message to the user using react-alert

https://www.npmjs.com/package/react-alert I want to show the alert message in my project using the. When the Update Button is pressed, I want the message to be displayed after updating, but it gives an error.

react-alert as I said through the site, but I'm making a mistake somewhere and I could not find the error. Can you help with this?

I wrapped the index.js file as instructed.

enter image description here

import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import {
  Button,
  Card,
  CardBody,
  CardHeader,
  Col,
  Row,
  Table
} from "reactstrap";
import Input from "reactstrap/es/Input";


import { useAlert } from "react-alert";

const alert = useAlert();

class CustomerDebt extends Component {
  constructor(props) {
    super(props);

    this.domain = `http://127.0.0.1:8000`;

    this.state = {
      isLoaded: true,
    };
    this.handleSubmitUpdate = this.handleSubmitUpdate.bind(this);
  }

  //Customer debt update
  async handleSubmitUpdate() {

    await fetch(`${this.domain}/api/debt/update/`, {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        id: this.props.id, //this.props.user.user_id,
        customer: this.props.customerInfo.customer.id,
        totalDebt: this.state.totalDebt
      })
    })
      .then(response => {
        return response.json();
      })
      .then(json => {
        this.componentDidMount();
        return( () => { alert.show("Update successfuly") })
      })
      .catch(err => console.log(err));
  }

  render() {
    const { isLoaded, items } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>

            <Row>
            <Col>
              <Card>
                <CardHeader>
                  <i className="fa fa-align-justify" /> Müşteri Borcu
                </CardHeader>

        <Button color="primary" onClick={this.handleSubmitUpdate.bind(this)} > {" "} Update </Button>{" "}

                <CardBody>
                  <Table hover bordered striped responsive size="sm">
                    <thead>
                      <tr>
                        <th width={"10"} />
                        <th width={"15"}>No</th>
                        <th width={"40"}>Total Debt</th>
                        <th width={"40"}>Received amount</th>
                      </tr>
                    </thead>

                    <tbody>
                      {items.map(item => {
                        return (
                          <tr key={item.id}>
                            <td>{item.id}</td>
                            <td>{item.totalDebt}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </Table>
                </CardBody>
              </Card>
            </Col>
          </Row>

        </div>
      );
    }
  }
}
export default CustomerDebt;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App/App';
import * as serviceWorker from './serviceWorker';

import { Provider } from 'react-redux';
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'


const store = createStore(
  rootReducers,
    allEnhancers
);

const options = {
    position: positions.BOTTOM_CENTER,
    timeout: 5000,
    offset: '30px',
    transition: transitions.SCALE
};

ReactDOM.render(
    <Provider store={store}>
        <AlertProvider template={AlertTemplate} {...options}>
            <App/>
        </AlertProvider>

    </Provider>,
document.getElementById('root'));


serviceWorker.unregister();

Upvotes: 1

Views: 2584

Answers (1)

Prijesh Meppayil
Prijesh Meppayil

Reputation: 540

Try HOC way with withAlert where alert will be available as a prop, as below:

import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import {
  Button,
  Card,
  CardBody,
  CardHeader,
  Col,
  Row,
  Table
} from "reactstrap";
import Input from "reactstrap/es/Input";


import { withAlert } from 'react-alert'

class CustomerDebt extends Component {
  constructor(props) {
    super(props);

    this.domain = `http://127.0.0.1:8000`;

    this.state = {
      isLoaded: true,
    };
    this.handleSubmitUpdate = this.handleSubmitUpdate.bind(this);
  }

  //Customer debt update
  async handleSubmitUpdate() {
    const { alert } = this.props;
    await fetch(`${this.domain}/api/debt/update/`, {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        id: this.props.id, //this.props.user.user_id,
        customer: this.props.customerInfo.customer.id,
        totalDebt: this.state.totalDebt
      })
    })
      .then(response => {
        return response.json();
      })
      .then(json => {
        this.componentDidMount();
        return( () => { alert.show("Update successfuly") })
      })
      .catch(err => console.log(err));
  }

  render() {
    const { isLoaded, items } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>

            <Row>
            <Col>
              <Card>
                <CardHeader>
                  <i className="fa fa-align-justify" /> Müşteri Borcu
                </CardHeader>

        <Button color="primary" onClick={this.handleSubmitUpdate.bind(this)} > {" "} Update </Button>{" "}

                <CardBody>
                  <Table hover bordered striped responsive size="sm">
                    <thead>
                      <tr>
                        <th width={"10"} />
                        <th width={"15"}>No</th>
                        <th width={"40"}>Total Debt</th>
                        <th width={"40"}>Received amount</th>
                      </tr>
                    </thead>

                    <tbody>
                      {items.map(item => {
                        return (
                          <tr key={item.id}>
                            <td>{item.id}</td>
                            <td>{item.totalDebt}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </Table>
                </CardBody>
              </Card>
            </Col>
          </Row>

        </div>
      );
    }
  }
}
export default withAlert()(CustomerDebt);

Upvotes: 1

Related Questions