Error: The promise was not caught due to a network issue, resulting in a creation error

I'm trying to use Axios for API communication and I keep encountering this error. Despite researching online and attempting various solutions, I am still unable to resolve the problem. Can someone please assist me? All I want is to be able to click on a button and see the low value in the developer tools.

  useEffect(() => {
    setJwt(getClientCookieFromClient('jwt'));
  }, []);

  const customFetch = async () => {
    const res = await axios
      .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
        headers: {
          Authentication: jwt,
        },
      })
      .then((res) => res.data);
    if (!res.data.success) {
      alert(res.data.message);
    }
  };

...

<button onClick={() => customFetch()}>Call API Button</button>

Answer №1

It is important to always enclose the await inside a try/catch block.

const customFetch = async () => {
  try {
    const res = await axios
      .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
        headers: {
          Authentication: jwt,
        },
      })
      .then((res) => res.data);
    if (!res.data.success) {
      alert(res.data.message);
    }
  } catch (error) {
    console.log(error);
    // Handle error appropriately
  }
};

Answer №2

Give this a shot

useEffect(() => {
    setJwt(getClientCookieFromClient('jwt'));
  }, []);

  const customFetch = async () => {
    const res = await axios.get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
      headers: {
        Authentication: jwt,
      },
    });
    if (!res.data.success) {
      alert(res.data.message);
    }
  };
  

Answer №3

Important Note:

Your response structure may need to be adjusted for optimal performance. The current code is functioning correctly with the following structure:

res = { data: { data: {success: true}}}

If this is not the case, consider using an if statement like !res.success


useEffect(() => {
    setJwt(getClientCookieFromClient('jwt'));
  }, []);

  const customFetch = async () => {
    const res = await axios
      .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
        headers: {
          Authentication: jwt,
        },
      })
      .then((res) => res.data)
      .catch((err) => console.log("Error while fetching", err)); // Use .catch to handle errors
    if (!res.data.success) {
      alert(res.data.message);
    }
  };

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 concealing an alert using an 'if' statement

There is an alert that pops up on a website only on specific days of the year. My query is: How can I make the alert hidden if the date is not one of those special days? I attempted the code below, but it seems to just delay the alert based on certain con ...

A guide to querying JSON data in a backend database with JavaScript

My backend JSON DB is hosted on http://localhost:3000/user and contains the following data: db.json { "user": [ { "id": 1, "name": "Stephen", "profile": "[Unsplash URL Placehol ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

troubleshooting issues with nextjs13 and styledcomponent

Greetings! Our team has recently updated to next.js 13 and react 18, and integrated styled components with the next config setting. However, we have encountered some unusual behaviors. One issue arises when extending styles, as shown below: const CardWra ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

Retrieve a Vue Component by utilizing a personalized rendering method for a Contentful embedded entry

Currently experimenting with Contentful, encountering some issues with the Rich text content field. To customize the rendering of this block and incorporate assets and linked references in Rich text content, I am utilizing the modules '@contentful/ri ...

Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout. <html data-ng-app="app"> . . . //menu section <li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat"> ...

Incorporate and interpret a custom JSON object within my Shopify Liquid theme

In an attempt to integrate custom data into my Shopify liquid theme, I stored a JSON file in the assets folder. My goal is to retrieve and parse this JSON object within a jQuery method from a JavaScript file also located in the assets folder. Despite try ...

Presenting a dynamic selection of files from a database in a dropdown menu with looping functionality using Laravel

I have a dropdown menu that I want to use to display input files from the database based on the selection made. Here is the scenario: When a dropdown option is chosen, it should show input files derived from the "loop_atachment" table (based on the select ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

"Development environment running smoothly for NextJS 14 site, but encountering issues when deployed on Verc

I am encountering an issue with my page (server component) that retrieves data from a route handler (/api/v1/bookings/get) within my application. While everything runs smoothly with next dev --turbo, deploying to Vercel results in the following error: App ...

Using ngFormModel with Ionic 2

How can I properly bind ngFormModal in my Ionic 2 project? I am facing an issue while trying to import it on my page, resulting in the following error message: Uncaught (in promise): Template parse errors: Can't bind to 'ngFormModel' since ...

Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below? html <div class="row"> <div class="col-sm-6"> <div cl ...

Issue with reCAPTCHA callback in Firebase Phone Authentication not functioning as expected

I have been working on integrating phone authentication into my NextJS website. I added the reCAPTCHA code within my useEffect, but for some reason, it does not get triggered when the button with the specified id is clicked. Surprisingly, there are no erro ...

Posting data in ASP.NET Core from the frontend to the backend (specifically with React) involves sending information

In my React code, I have a function to hit the API when the submit button is clicked. I update the question and add a new class called httpresponemessage post. const handleOnPreview = (e) => { e.preventDefault(); setsubmittext(text); ...

The NextJS API route functions flawlessly when tested locally, generating over 200 records. However, upon deployment to Vercel, the functionality seems to

Here is the API route that I am using: https://i.stack.imgur.com/OXaEx.png Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import axios from "axios"; import prisma from "../../../lib/prisma ...

Revamp the HTML page by automatically refreshing labels upon every Get request

My HTML webpage requires real-time updates for one or more labels. To achieve this, I have incorporated CSS and JS animations into the design. Currently, I am utilizing Flask to handle all the calls. I face a challenge where I need to consistently update ...

Having trouble with images not showing up when using Material UI components within a Next.js route

I am currently working with Material UI and Next.js. Below is the code snippet I am using: import { Container, Grid, Paper } from '@mui/material'; import { useState } from 'react'; import { styled } from '@mui/material/styles' ...

Tips for adjusting the MUI datagrid's display mode specifically for mobile users

In my React project (version 18.2.0), I'm utilizing the MUI datagrid from the community edition version 5.17.22. My goal is to adjust how the datagrid renders rows and columns specifically for mobile devices. To better illustrate my point, I have incl ...

What steps do I need to take to activate the AWS Location Services map in a React application, allowing unauthenticated users through AWS C

Currently, I'm developing a react application that incorporates a map by utilizing AWS Location Services. Instead of relying on the tutorial's implementation of user authentication through AWS Cognito, which conflicts with our in-house authentica ...