How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all routes. Can anyone guide me in identifying what I might be doing wrong? Thank you.

Below is the axios request function:

export const getAllUsers = async (): Promise<IResponse | IErrorResponse> => {
    const axiosClient = AxiosClient.createInstance();
    try {
        const response = await axiosClient.get("/api/v1/getAll");

        return {
            success: true,
            data: response.data
        };
    } catch (err) {
        console.error(err);

        return {
            success: false,
            data: isAxiosError(err) ? err.message : (err as string)
        };
    }
};

And here is the ReactJS part of the code:

const App = () => {
    const [users, setUsers] = useState<userData[]>([]);

    useEffect(() => {
        // View browser console for the result
        const getUsers = async () => {
            const response = await getAllUsers();
            if (response.success) {
                setUsers(response.data as userData[]);
                console.log(response.data);
            } else {
                throw Error("Cannot fetch"); // temporary error handling
            }
        };
        getUsers()
    }, []);

    return (
        <div>
            {users && users.map(user => <li>{user.name}</li>)}
    </div>
    )
}

Answer №1

When useEffect is used within the app component, and since the App component serves as the main component, it gets called on every page load. To optimize this, consider moving your logic to a separate component and implementing routing so that it only gets called on the specific route where it is needed.

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

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Using TypeScript to retrieve a strongly typed promiseValue from an angular $modalInstanceA

New to TypeScript Question: I'm working on returning a strongly typed promise from angular's $modalInstance. Here is an example of what I have: this.$modal.open(options).result.then(result => { At the moment, 'result' is of typ ...

Adjust the value of a cell in the MUI Data Grid in real-time

In the Data Grid, there are 9 columns including "Rate" and "Transfer". There is also a column labeled "Total" which should display the multiplication result of "Rate" and "Transfer", adjusting with any changes made to the "Transfer" cell value. The "Transf ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

When attempting to transfer data to a CSV file from my Firebase database, I encounter an issue where the

I am facing an issue with exporting data from my Firebase Firestore to a .csv file. I have followed all the necessary steps, but whenever I try to add the values for export, they show up as undefined. While I am not an expert in React and consider myself ...

Error: Unable to access the 'error' property because it is undefined

I have already defined the error, but I am getting an error message stating "TypeError: Cannot read property 'error' of undefined". I am stuck here and would appreciate any ideas on how to move forward. Thank you for your assistance. Error scr ...

'value' is connected to every single hook

Every time I try to save my work using any hook, the 'value' field changes automatically. This has been causing me a great deal of stress. I would be extremely grateful if someone could assist me with this issue. click here for image description ...

Organizing string enum in Typescript and AngularJS - Tips and Tricks

In my Typescript file, I have defined an enum called PriorityLevel: enum PriorityLevel { High = <any>'High', Normal = <any>'Normal', Low = <any>'Low'} In the HTML section, I have the following code: <b ...

The manager encountered an issue while querying for "Photo" data: EntityMetadataNotFoundError - no metadata could be found

I encountered an error while attempting to utilize typeorm on express: if (!metadata) throw new EntityMetadataNotFoundError(target) ^ EntityMetadataNotFoundError: Unable to locate metadata for "Photo". Below is my data source: import " ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

Utilize the same variable within a React functional component across multiple components

Within a React functional component, I am utilizing the following constant: const superHeroPowers = [ { name: 'Superman', status: superManPowerList }, { name: 'Batman', status: batmanPowerList }, { name: 'Wonder Woman&a ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

"Encountering an issue where attempting to set a property on an undefined variable, despite it being

I've been working on a timer app/component, but I'm running into an issue. The error message reads: Cannot set property startAt of undefined. I've defined it in my dashboard component, so I'm not sure where the problem lies. Any suggest ...

Creating a feature that allows users to edit the order of items within a MySQL

I am working on a project where I need to display a table of items that can be added, deleted, and reordered by the user. Initially, I planned to store these items in a MySQL database with an order column in the table. However, I realized this method is in ...

The image source is unable to locate the image

Adding an image to my React component is proving to be problematic as the alternative text keeps being displayed instead. In the Navbar component, this is how I am trying to include the image: <img src="../assets/images/nav_logo.png" alt=&quo ...

After utilizing the d3-scale function to declare an object, my developer visual suddenly ceases to function

Upon completing a section of a Power BI tutorial, the developer encountered a visual that displayed nothing but a blank page (despite running correctly). Unable to pinpoint the issue, debugging was initiated. The following test code snippet for debugging w ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...