Question:
How to show status with red / green background depending on axios post result

Solution

The color red and green of the status depend on the result of an Axois POST request by managing the component state.


To show the error status in addition to the message, you'll need to use several state variables or add extra information to your state.


Using an object with type and message properties, try something similar.


setStatus(null);

try {

  const data = { user, name, ipaddr, port, sshuser, sshpass, sshport, license };

  const res = await axios.post('/exec/addcontroller', data, {

    headers: {

      Authorization: token,

    },

  });

  setStatus({

    type: 'success',

    message: `Controller ${name} added successfully`,

  });

} catch (err) {

  setStatus({

    type: 'error',

    message: err.response?.data.message ?? 'An error occurred',

  });

}


and render it like this


{status && <div className={`alert ${status.type}`}>{status.message}</div>}


You could use an id instead of className but I feel CSS classes make more sense here.


.alert {

  border: 1px solid;

  padding: 5px;

}


.alert.error {

  color: #ff0040;

  background-color: #f8e0e6;

  border-color: #f7819f;

}


.alert.success {

  color: darkgreen;

  border-color: darkgreen;

  background-color: lightgreen;

}


Note that I removed the Content-Type header from the request. It was completely redundant in this case.


Answered by: >Phil

Credit: >StackOverflow


Suggested Blogs

>How to persist data between two different requests in a controller?

>How to fix routes in Laravel?


Submit
0 Answers