Revamp the Next.js and TypeScript API for improved efficiency

I am new to using Next.js and TypeScript, and I would like to refactor my code to improve data fetching speed.

Currently, I have a file called dashboard.tsx with the following code:


    import Layout from "@/layouts/layout";
    import React, { useContext, useEffect, useState } from "react";
    import { LanguageContext } from "@/hooks/Lang/LanguageContext";
    // More imports...

    const Dashboard = () => {
      // State variables and functions...

      const fetchData = async () => {
        // Data fetching logic...
      };

      const handleAccept = async (id: number) => {
        // Accept handling logic...
      };

      const handleReject = async (id: number) => {
        // Reject handling logic...
      };

      useEffect(() => {
        // Fetching data on component mount...
      }, []);

      return (
        <Layout>
          {/* JSX structure... */}
        </Layout>
      );
    };

    export default Dashboard;
  

The current implementation involves multiple parallel API calls, resulting in slow loading times. I am seeking advice on how to refactor this code for better performance. Any suggestions on improving the speed or refactoring techniques would be greatly appreciated. Thank you!

This is the getMultipleData function:


    import { callApi } from '@/hooks/callApi'
    
    const defaultRoute = '/api/app';
    
    export async function getMultipleData(url: string) {
      return await callApi('get', defaultRoute + url)
    }
  

P.S. I am using Laravel for the backend. Any feedback on improving my coding patterns would also be helpful. I have tried using useMemo from React, but I am unsure if it is related to what I am trying to achieve.

Answer №1

Here are a few suggestions to enhance the efficiency and sleekness of your code:

  1. Consider leveraging the Promise.allSettled feature in JavaScript to efficiently manage multiple API calls.
  2. You may be able to streamline your code by consolidating some of your states into an object and updating only specific properties when necessary.
  3. Using the Axios library for your API calls is highly recommended.

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

Utilizing the Next.js "Link" Element as a Personalized React Component Using Typescript

When attempting to utilize the "Link" element as a custom react component that I modified with typescript to enhance its functionality, I encountered a recurring issue in my project. Each time I used it, I had to include a property named props which contai ...

The issue occurs when using NextJS in conjunction with React-Query, where the query disappears from the React-Query DevTools after clicking on the link for a

Using the react-query hook export const useSearchClient: UseSearchClient = (filters) => { return useQuery({ queryKey: ['clients'], queryFn: queryFn(filters), enabled: false, }) } Implementing the client component const { data, ...

I ran into a problem while trying to install next.js

I am currently setting up Next.js for the first time on my Mac terminal using the command <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74170611150011591a110c00591504043445405a465a47">[email protected]</a>. Prior ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

The supplied client secret does not correspond to any SetupIntent associated with this account

I am currently working on linking an external bank account to a Stripe connected account, specifically a custom account type. I have successfully created a SetupIntent associated with the connected account, generated a client secret as shown below: params ...

Cypress encountered an error: Module '../../webpack.config.js' could not be located

Every time I attempt to run cypress, an error pops up once the window launches stating "Error: Cannot find module '../../webpack.config.js'" Within my plugins>index.js file, I have the following in module.exports webpackOptions: require(&apos ...

What could be causing my function to return as undefined the second time it's invoked?

Within my approach private onDataLoadSuccessful(users: User[], roles: Role[]) { this.alertService.stopLoadingMessage(); this.loadingIndicator = false; this.dataSource.data = users.map(data => { let newData: User; newData = ...

Error: Unable to locate script.exe when spawning the Nodejs process

When trying to run an exe in my electron app, I am encountering an error. Even though the path is correct, it still throws an error. Uncaught Error: spawn exe/0c8c86d42f4a8d77842972cdde6eb634.exe ENOENT at Process.ChildProcess._handle.onexit (inter ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

Utilizing background images in Next.js with Style JSX

I'm feeling a bit lost when it comes to using NextJS and the background property. Within a component, I am attempting to create a hero section but I'm struggling with how to implement it in style jsx. This is my component : const homeTitle = ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. I have designed a visually appealing travel landing page, , featuring a thumbnail carous ...

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

Angular HttpClient Catch Return Value

In my quest to develop a universal service for retrieving settings from the server, I've encountered an issue. When errors arise, I want to intercept them and provide a default value (I have a predetermined configuration that should be utilized when e ...

Combining TypeScript with Vue3 to implement bootstrapVue

After using BootstrapVue as any, the error was corrected but unfortunately it still doesn't work in the browser. Here is what's inside main.ts: import { createApp }from 'vue'; import App from './App.vue'; import router from & ...

Guide to creating a Unit Test for an Angular Component with a TemplateRef as an Input

Looking to create unit tests for an Angular component that can toggle the visibility of contents passed as input. These inputs are expected to be defined as TemplateRef. my-component.component.ts @Component({ selector: "my-component", templateUrl ...

Error: Unable to access 'price' property of undefined - Next.js version 14.0.1

I'm encountering an issue with Next.js where my code is not working as expected. Interestingly, the same code works perfectly fine in other templates. let subTotal = 0 if (selectedProducts?.length) { for (let id of selectedProducts) { ...

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

The React error message "Unrecognized property key detected: react/no-unknown-property"

I encountered an error while uploading my Next.js app to Vercel. Can someone please assist me in resolving this issue? https://i.sstatic.net/6qxOF.png ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...