Home > Mobile >  How can I show alert dialog after axios http methods?
How can I show alert dialog after axios http methods?

Time:08-11

I'm trying to add color by using the post method with axios in react. The backend side works very well. I can add a color, but I want an alert dialog to appear on the screen. if an error is encountered then show an error message when adding . Every time I press the button, it doesn't work, only if the axios operation is successful, the successful alert dialog will appear. If there is an error, the error alert dialgo should appear. I'm new to react so I dont know actually how to apply it my codes.

AddColor.js

import axios from "axios"
import { useState } from "react";


export default function AddColor() {


    const [Name, setcolorName] = useState('');
   

    const handleSubmit = (e) => {

        e.preventDefault();

        axios({
            method: 'post',
            url: 'http://localhost:64082/api/color/add',
            data: {
                Name
            }
        })
        

    }


    return (

        <div className="create">
            <h2>Add a New Color</h2>
            <form onSubmit={handleSubmit}>
                <label>color Name:</label>
                <input
                    type="text"
                    required
                    value={Name}
                    placeholder="please enter color name..."
                    onChange={(e) => setcolorName(e.target.value)}
                />

                <button>Add Category</button>
            </form>
        </div>
    )

}

CodePudding user response:

I did a codesandbox.io to explain to you how to do it using async/await syntax. I will paste the results here.

import { useState } from "react";
import axios from "axios";

export default function App() {
  const [Name, setcolorName] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      await axios({
        method: "post",
        url: "https://httpstat.us/200",
        data: {
          Name
        }
      });
      return alert("Success!");
    } catch (error) {
      return alert("Error: "   error);
    }

  };

  return ( ...

CodePudding user response:

You can use the axios .then and .catch to update your states and show popup in function.

axios({
   method: 'post',
   url: 'http://localhost:64082/api/color/add',
   data: {
      Name
   }
})
.then((res) => {
   // here show your success popup
})
.catch((err) => {
   // here show your error popup
})

CodePudding user response:

Axios has a method called .catch() (link).

axios({
    method: 'post',
    url: 'http://localhost:64082/api/color/add',
    data: {
        Name
    }
}).catch((error) => {
    console.alert(error.response.data || "Code 500: Internal Server Error")
})
  • Related