Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

468
Vistas
Is there a more efficient way to fetch data from an API using axios? (React.js & node.Js)

In this implementation, the code runs and achieves the purpose of what I am trying to do — use axios to fetch the dummy API at https://jsonplaceholder.typicode.com, then display it on the screen. However, I feel my code could be refactored to become more efficient. Currently, I have four useState constants (one for each property in the object), which are set/updated upon fetching. I tried to consolidate the CurrentFetch CurrentFetch2 CurrentFetch3 CurrentFetch4 constants into a single useState({})object, but React was giving me errors for using objects here. Any ideas?

Here is my code:

import React, { useState } from "react";
import "./App.css";
import axios from "axios";

function App() {
  const [fetchCount, setFetchCount] = useState(1);
  const [currentFetch, setCurrentFetch] = useState([]);
  const [currentFetch2, setCurrentFetch2] = useState([]);
  const [currentFetch3, setCurrentFetch3] = useState([]);
  const [currentFetch4, setCurrentFetch4] = useState([]);


  const HandleFetchApi = async () => {
    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${fetchCount}`)
      .then((response) => {
        let data = response.data;
        setCurrentFetch(data.userId);
        setCurrentFetch2(data.id);
        setCurrentFetch3(data.title);
        setCurrentFetch4(data.completed);
        setFetchCount(fetchCount + 1);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  return (
    <div className="App">
      <h1>Testing API Fetch from Dummy Api</h1>
      <button onClick={HandleFetchApi}>
        Click to fetch record #{fetchCount}
      </button>
      <h2>user id: {currentFetch}</h2>
      <h2>id: {currentFetch2}</h2>
      <h2>title: {currentFetch3}</h2>
      <h2>completed: {currentFetch4.toString()}</h2>
      <br />

      <h5>from: https://jsonplaceholder.typicode.com/</h5>
    </div>
  );
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Better version:

import React, { useState } from "react";
import "./App.css";
import axios from "axios";

function App() {
  const [fetchCount, setFetchCount] = useState(1);
  const [currentFetch, setCurrentFetch] = useState({
    userId: '',
    id: '',
    title: '',
    completed: ''
  });


  const HandleFetchApi = async () => {
    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${fetchCount}`)
      .then((response) => {
        const { userId, id, title, completed } = response.data;
        setCurrentFetch({...currentFetch, ...{userId, id, title, completed}});
        setFetchCount(fetchCount + 1);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  return (
    <div className="App">
      <h1>Testing API Fetch from Dummy Api</h1>
      <button onClick={HandleFetchApi}>
        Click to fetch record #{fetchCount}
      </button>
      <h2>user id: {currentFetch.userId}</h2>
      <h2>id: {currentFetch.id}</h2>
      <h2>title: {currentFetch.title}</h2>
      <h2>completed: {currentFetch.completed.toString()}</h2>
      <br />

      <h5>from: https://jsonplaceholder.typicode.com/</h5>
    </div>
  );
}

export default App;

Happy Coding :)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda