Duplicate axios calls in react

Viewed 1141

I am working on a create-react-app generated app and I have an API call to a local JSON file. Somehow this code generates 8 API calls in a roll.

import '@css/request.scoped.css';
import { useState } from 'react';
import { getAllData } from '@api/api';

function Request() {
  let [user, setUser] = useState('');

  function changeUser(data) {
    setUser(data);
  }

  getAllData().then((reply) => {
    changeUser(reply.data[0].item_name);
  });

  return <>{user}</>;
}

export default Request;

and here is my Axios instance

import axios from "axios";

const request = axios.create({
  baseURL:'./example.json',
  timeout: 20000,
});

export const getAllData = () => {
  return request({
    method: 'get',
    url: '',
  });
};

Can someone tell me why this happens?

1 Answers

I suspect the most likely cause is that the component is being re-rendered, and currently the logic is to make the API call on every render.

You can set the logic to occur only on the first render of the component with useEffect:

import { useState, useEffect } from 'react';

// then...
useEffect(() => {
    getAllData().then((reply) => {
        changeUser(reply.data[0].item_name);
    });
}, []);

The empty dependency array passed to useEffect means it would open happen once when the component is first loaded, not on subsequent renders. Any dependency you add to that array would cause the operation to be invoked again any time that dependency changes between renders.

Related