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;
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 :)