I would like to know how to correctly load data before rendering in React.
I have app, that fetchs data about Star Wars character from API and renders it on the page. I want also to fetch next character data before i want to render it by clicking on the button. I have an example of this app:
`
function fetchData(count, setState) {
fetch("https://swapi.dev/api/people/" + count)
.then(res => res.json())
.then(data => setState({
id: count,
name: data.name,
birth_year: data.birth_year,
gender: data.gender
}))
}
function App() {
let [data, setData] = React.useState({});
let [preloadedData, setPreloadedData] = React.useState({});
let [count, setCount] = React.useState(1);
React.useEffect(() => {
if (count === 1) {
fetchData(count, setData)
fetchData(count + 1, setPreloadedData);
}
else {
setData(preloadedData)
fetchData(count + 1, setPreloadedData);
}
}, [count]);
console.log(count)
return (
<main>
<h1>Starwars character data</h1>
<p><span>Number:</span> {data.id}</p>
<p><span>Name:</span> {data.name}</p>
<p><span>Birth year:</span> {data.birth_year}</p>
<p><span>Gender:</span> {data.gender}</p>
<button onClick={() => setCount(count + 1)}>Next character</button>
</main>
)
}
`
I have 2 questions: 1)is this a correct way of solving my problem, or there can be better practices? 2)I guess this way still could be better, because console.log is called 3 times, so my component renders 3 times each time the count state is changed, and it could be less?
Would like to know your opinion