Ways to exhibit error messages on a webpage using axios in the front end,

Here is my fast API endpoint:

@app.post("/api/signup", status_code=status.HTTP_200_OK)
async def signup( credentials : signupcred ):
  try: 
   print(credentials.email,  credentials.password1, credentials.name )
   response = account.create(email= credentials.email, password= credentials.password1, name = credentials.name , user_id= ID.unique() )

   return {response}

  except Exception as e: 
         raise HTTPException(status_code= status.HTTP_403_FORBIDDEN)  # Return an appropriate error status code

When an exception is raised, I want to display the response on the front end. The response provides a detailed explanation of the error and I don't want to send an HTTP error code to the user.

This is my front end code:

const handlesignup = async (e: any) => {
  e.preventDefault();
  setLoading((loading) => !loading);
  try {
    const signupresponse = await axios.post("/api/signup", {
      email: signupemail,
      password1: password1,
      name: name,
    }); // Send as query paramers );
    // const loginresponse = await axios.post('/api/login', {email, password} )// Send as query paramers );
    // setIsloggedin(()=> true)
    router.replace("/dashboard");
    setLoading((loading) => !loading);
  } catch (error) {
    alert(error);
  }
};

The console.log feature doesn't work due to using Next.js with a FastAPI backend. I simply want to display the response from the create function on the front end so users can understand why an error occurred. Currently, the alert displays: AxiosError: Request failed with status code 403

Answer №1

For more information on how to handle errors with Axios, check out Axios - Handling Errors

If you need to access the response body, you can use error.response?.data.

In a Next.js component, you would typically manage this information using React state, like so:

const [error, setError] = useState<string>();

const handlesignup = async (e: any) => {
  e.preventDefault();
  setError("");
  setLoading(true);
  try {
    const signupresponse = await axios.post("/api/signup", {
      email: signupemail,
      password1: password1,
      name: name,
    }); // Send as query paramers );
    // const loginresponse = await axios.post('/api/login', {email, password} )// Send as query paramers );
    // setIsloggedin(()=> true)
    router.replace("/dashboard");
  } catch (error) {
    console.warn('Signup failed', error);
    setError(error.response?.data ?? error.message);
  } finally {
    setLoading(false);
  }
};

if (error) {
  return <p className="error">{error}</p>;
}

Answer №2

To clarify, it seems like you are suggesting using another useState<AxiosError>() so that in the .catch(error) block, you can call setError(error). Then, in the component being returned, you would be able to display the error message...

return (
    <div> 
        ...
        {error && error.response.data.message}
    </div>
);

If you're unsure about the exact path to the message in AxiosError, you could try inspecting it on Typescript by pressing F12 and exploring its types.

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

Tips for displaying indentations on Tube Geometry using THREE.js

Currently, I have a project where I am tasked with displaying dents on a pipeline in a 3D format. To create the pipeline, I utilized THREE.js's tube geometry which is illustrated below: <!DOCTYPE html> <html lang="en"> <head> ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

Are you looking to apply the function to each item separately?

Looking for assistance in resizing input fields dynamically using jQuery. Currently, the function I have is working but it's setting the same width value for all inputs instead of each input having its own independent width. Can anyone spot what might ...

Scrape data from websites where the main URL remains constant but the information in the table varies

If you take a look at this link, you'll notice that when the next page is selected, the table on the website gets reloaded with new content without any change in the URL. Even after inspecting the developer tools > Network > XHR, it's diffi ...

Navigating through a DOM string in Nuxt.js

I'm in search of a solution to parse a string containing DOM elements within Nuxt.js. The challenge lies in finding a parser that functions seamlessly on both the client and server side. Thus far, I've come across options that are limited to eit ...

Learn how to increase spacing in React applications

I'm currently utilizing the Grid component from @material-ui to present my data. Within this Grid, I have several nested grids, each representing a different section. I've implemented the container spacing attribute of the Grid and set it to the ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Unable to refresh page in Angular without hashtag is causing issues

My web application is built using Spring, Angular, and Rest. I successfully removed the hashtag from the URL by implementing the following code: if(window.history && window.history.pushState) { $locationProvider.html5Mode(true); } in index.ht ...

Modify the background color of a specific bar across multiple charts when hovering or clicking - utilizing chart.js

I have multiple chart.js canvas elements on a webpage. The goal is to be able to quickly identify and highlight the same bar value across all the charts. For example, when I hover over a bar called "Thu" on the first chart, I want to automatically search f ...

Having trouble retrieving data from Redux in React

I'm struggling to load data from my state into a form. After logging in and saving the email and token into Redux state, I encounter an issue when trying to display the email within the form on a test page. Despite being able to see the email on TestP ...

JavaScript: Check array before adding new item to avoid duplicates

Is there a way in JavaScript to determine if an item already exists in an array? I am using the following code to add items to my array: const booked_hours = []; for (let i = 0; i < apptid_set.size; i++) { const book_hours = [...book_tim ...

How to Make Buttons Vanish and Reappear

Check out this fiddle for a picture button 'scroller' that I created. It may not be perfect, but my main focus is on making the arrow buttons fade in and out when reaching the end of the picture order. I am considering using a JavaScript functio ...

Ways to establish cache in a server-side next.js environment

Having issues with 'node-cache' implementation in my Next.js backend. Below is the code for my cache file: cache.ts import NodeCache from 'node-cache'; const Cache = new NodeCache({ stdTTL: 60 * 60 * 6 }); // 6 hours export default Cac ...

What causes the 'find' query to return a Query object instead of the expected data in MongoDB?

After researching extensively on SO, I have yet to find a solution to my ongoing issue. Currently, I am in the process of developing a project using node, express, and mongodb. To start off, I created a seeder file to populate some data into mongodb: var ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

How to work with a JSON object in Internet Explorer 6

Looking for some quick answers that should be easy for someone with expertise to provide. I have a basic asp.net site that relies on JSON for various tasks (and JSON.stringify). Everything works fine in Firefox and the like, but in IE6 I'm getting a ...

Mantine UI: Elevate Your Component Library Experience

I am in the process of creating a Component library for internal company projects, which will be packaged as an npm package. To kick things off, I am starting with Mantine and plan to incorporate customization using tailwind CSS. As a test, I have created ...

Arranging data by last name when the first and last names are combined in a single field of the

My datatable is set up with basic fields and data rows, including a column for customer names that combine both first and last names. Is there a way to modify the sorting method in datatables to sort based on the surname (last word) within this column? ...

Creating an array in Angular/TypeScript that contains another array and a variable

I hate to admit it, but I found myself struggling with a simple task the other day - creating an array. Let me explain my dilemma. I am trying to populate an array in the following format: fatherArray=[ { tagName: '', list:[] ...