Attempting to capture a previously unhandled error thrown by Axios when utilized in conjunction with React Query (with suspense mode enabled) within a NextJs application

Utilizing NextJS, React query (with axios and suspense mode), I am attempting to handle an intentional 404 error from my API. Although I successfully caught it in my error.js file, the same error still shows up in the console as "uncaught." https://i.stack.imgur.com/J0yCx.png

I have also made attempts to log and catch this error in my component where I use the react query, but despite being able to log it, it continues to display as "Uncaught" in the console.

Here is my Home component: https://i.stack.imgur.com/I0Aq0.png

My route: https://i.stack.imgur.com/RAm3E.png

And my error.js file: https://i.stack.imgur.com/uLdKc.png

Any suggestions on how to effectively catch this error?

Answer №1

It seems like the issue lies in your error.js file not properly handling the 404 Error that occurred. The GlobalError component is only logging the error generated by the useEffect().

To address this, I recommend implementing the ErrorBoundary Component to effectively display an error message (in this case, indicating that an error has occurred!)

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
 
    // Initialize state variable to track error occurrence
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    // Update state to display fallback UI upon error
 
    return { hasError: true };
  }
  componentDidCatch(error, errorInfo) {
    // Implement custom error logging service here
    console.log({ error, errorInfo });
  }
  render() {
    // Check if error has been caught
    if (this.state.hasError) {
      // Display custom fallback UI in case of error
      return (
        <div>
          <h2>An error occurred</h2>
          <button
            type="button"
            onClick={() => this.setState({ hasError: false })}
          >
            Try again?
          </button>
        </div>
      );
    }
 
    // Render children components if no error occurred
 
    return this.props.children;
  }
}
 
export default ErrorBoundary;

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

The ThemeProvider does not automatically provide theme injections

After creating a theme using the createTheme method from @mui/material/styles, I attempted to apply this theme using ThemeProvider from the same package. This snippet showcases the dark theme that was created: export const darkTheme = createTheme({ pale ...

What are the drawbacks of utilizing the onClick function in JavaScript?

What is the rationale behind programmers opting not to use onClick function in Javascript? ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Automate the input provided to yeoman command line interface for implementing CI/CD tools

When executing Yeoman, it prompts for input one by one. Is there a way to provide all inputs at once or programmatically? For instance: yo azuresfguest It requests 5 inputs to be added, which I would like to provide in one go for running in a CI/CD syst ...

JavaScript finding items in an array

The main issue I am encountering involves receiving a notification when the term (city name within the project) entered by the user in JqueryUI Autocomplete does not match anything in the collection (e.g. user entered "My Sweet City" and it does not matc ...

Interference in the output of .innerHTML leads to disruption

I have been working on a feature to display a calculated price based on the selected quantity for each individual product. I attempted to duplicate the code and modify variable names, but encountered issues with the increase/decrease buttons triggering mul ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

Utilizing NextJS and NextAuth to Detect Customer Subscription Status

I created a shopping app with NextJS that uses NextAuth for authentication, specifically the CredentialsProvider. Everything is working well and upon successful authentication, I store the customer_id and name in the session. The issue I'm encounteri ...

What could be the reason for Firebase automatically deploying my Next.js application to both Firebase Hosting and Functions?

I have a Next.js app that I deployed to Firebase. I utilized an experimental feature provided by Firebase for deploying my Next.js app. Firebase deployed my Next.js app to both hosting and functions, giving me access to the app through both links. What i ...

The back button on an Angular JS application should display a confirmation dialog when pressed

I am currently working on an AngularJS mobile app that consists of various modules. One of my requirements is to access the device's back button within the application, and I also need a dialog with "OK" and "Cancel" options. Clicking on "OK" should ...

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

Automated configuration of AWS Amplify JavaScript using Gitpod

Looking to streamline the setup process for an AWS Amplify JavaScript project on Gitpod. My goal is to eliminate the manual steps of configuring the amplify-cli, such as adding IAM users and generating the aws-exports.js file. Successfully installed the a ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

What is the best way to scale down my entire webpage to 65%?

Everything looks great on my 1920x1080 monitor, but when I switch to a 1024x768 monitor, the content on my webpage becomes too large. I've been manually resizing with CTRL+Scroll to reduce it to 65%, which works fine. Is there a code solution using CS ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

The byte order of integer literals in JavaScript

When writing the following line in Javascript: var n = 0x1234, is it always true that n == 4660? This question could also be phrased as follows: Does 0x1234 represent a series of bytes with 0x12 as the first byte and 0x34 as the last byte? Or does 0x1234 r ...

Utilize React to selectively execute either Server-Side Rendering or Client-Side

My current website utilizes SSR (using nextJS) to display the landing page in the root directory. However, I am interested in having my create-react-app application displayed when a user is logged in, and revert back to showing the landing page when they a ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

Ways to access states from a Vuex store within a Vuetify list in VueJs

Here is a snippet from my Vue file: import store from '@/store' export default{ name: 'myList', data: () => ({ show: true, listContent: [{ name: '1', icon: 'pers ...