PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How can I show alert dialog after axios http methods?

 October 13, 2022     axios, javascript, reactjs     No comments   

Issue

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>
    )

}

Solution

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 ( ...


Answered By - Caio Gomes
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing