Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights.

Here is the code snippet from utils.ts:

enum HTTPMethods {
  GET = "GET",
  POST = "POST",
  PUT = "PUT",
  PATCH = "PATCH",
  DELETE = "DELETE",
}

function handleError(status: number, message: string) {
  throw new Error(`${status}: ${message}`);
}

async function request<TResponse>(
  url: string,
  config: RequestInit
): Promise<TResponse> {
  const response = await fetch(url, config);
  if (!response.ok) {
    handleError(response.status, response.statusText);
  }
  return await response.json();
}


export async function _get<TResponse>(url: string): Promise<TResponse> {
  return request<TResponse>(url, { method: HTTPMethods.GET });
}

export async function _post<TBody extends BodyInit, TResponse>(
  url: string,
  body: TBody
): Promise<TResponse> {
  return request<TResponse>(url, { method: HTTPMethods.POST, body });
}

Inside page.tsx:

//imports

const { products } = await _get<ProductsType>(
 `${process.env.CLIENT_API_URL}/products`
);

//return

Lastly, in types.d.ts:

type ProductType = {
  id: number;
  title: string;
  description: string;
  price: number;
  // other properties
};

Answer №1

Implementing a variety of functions to facilitate the sending of GET/POST requests can be useful. However, determining whether this is the most efficient methodology ultimately depends on your individual preferences and project requirements. While such functionalities may expedite coding processes, they can also introduce certain limitations.

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

SQL Procedure for Inserting Dynamic Data into MSSQL

Can a stored procedure be created to accept two parameters (Table_Name, Rows) where the rows are in a standard format such as JSON? For example: INSERT("TABLENAME","{{id:1,Code:'AA'},{id:2,Code'BB'}}") Or can it be in any other format ...

Troubleshooting the Issue of PHP Variables Not Being Assigned to Javascript Variables

I am currently struggling with an issue. I am trying to assign a PHP value to a variable in Javascript. Here is what I have attempted: <script> JSvariable = <?php echo $PHPvariable; ?>; </script> However, this approach is not yieldi ...

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

Obtain the URL link from Unsplash where the picture is sourced

As I work on a website, I incorporate a link () to display a random photo. However, the photo refreshes periodically and upon loading the site, all that is visible is this default link: . Is there a method to extract the actual source like so: "". Althou ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

What is the method for displaying an object as JSON on the console in Angular2?

I've been utilizing a service to input my form data into an array within my angular2 application. The information is organized in the following manner: arr = [] arr.push({title:name}) After executing console.log(arr), it displays as Object. However, ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

In certain situations, the JavaScript code runs either before or after the print dialog is displayed when using the window

I am facing an issue with the print function on my web page. I want to display a thank you message to the user after they have either printed or cancelled the print dialog. Below is a simplified version of the print function code: function printThenThank ...

When utilizing AngularFire with Firebase Firestore Database, users may encounter instances where data duplication occurs on

Currently facing a challenge in my Angular 13.1 Project utilizing @angular/fire 7.4.1 for database management The issue arises consistently across various screens where data from Firestore Database is displayed, particularly on List screens. The lists are ...

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

Retrieving information from incoming JSON within a Java servlet

I have a client sending me a JSON file via HTTP PUT. Here is the content of the file: { "nomPers": "Testworking", "prenomPers": "WorkingTest", "loginPers": "Work", "pwdPers": "Ing", "active": true }, For my WebService framewo ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

Associating specific information with individual elements utilizing HTML text box

Seeking guidance on implementing annotations feature for a scatter-plot using d3.js v3. My goal is to show a text-box upon clicking each data point, then display that entered text as a tool-tip specific to that data point. Here's how I'm approach ...

What is the reason behind the necessity for a React class component to always invoke super(props) within its constructor function?

I recently came across a tutorial from reactjs.org that mentioned the importance of calling the base constructor with props in class components. However, further research led me to a StackOverflow answer suggesting that super() can be used instead of super ...

Using get_json() in Flask server is not possible when JSON data is sent from an Android device using MultiPartEntityBuilder

My aim is to send a JSON formatted string from an Android device to a Flask server. To achieve this, I am utilizing Apache MultiPartEntityBuilder for sending, as I also need to include an image file in the same http post message. While I have successfully ...

What is the process for transferring an image from the main page to another?

For days, I have been searching for an answer without any luck. It seems that I just can't wrap my head around it and apply it to what I am working on. Currently, I am using PHP to store images on the server when a user hits submit. My goal is to dis ...

Revamping Slideshows: Bringing CSS Animation to JavaScript

/* JavaScript */ var slides=0; var array=new Array('background.jpg','banner.jpg','image.jpg'); var length=array.length-1; $(document).ready( function(){ setInterval(function(){ slides++; ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...