'How to not render anything in react, unless data is loaded and state is completely set
Let's consider this code:
const CustomersList = () => {
const [loading, setLoading] = useState(true);
const [customers, setCustomers] = useState([]);
useEffect(() => {
// fetch customers from an API and then
// setLoading(false)
// setCustomers(customersArrayFromApi)
}, [])
return loading
?
<div>Loading ...</div>
:
<div>
{customers.length === 0
?
<span>No customer</span>
:
<div>List of customers rendered here</div>
}
</div>
}
When I setLoading(false) and setCustomers(customersArrayFromApi), there is this tiny timeframe (even for a millisecond or less than that) that the <span>No customer</span> is rendered.
And we know it's because react's state setting function is async.
But I can't render JSX in useEffect to wait for customers array to be set fully.
What can I do to wait for the customers list to be fully set, and then render the output?
Solution 1:[1]
Change the order of setState in useEffect, set the loading false after updating the customers.
And we know it's because react's state setting function is async.
React may batch the setState calls and the state updates may happen asynchronously but batching won't work inside async operations like fetch until React 17.
useEffect(() => {
// fetch customers from an API and then
setCustomers(customersArrayFromApi); //Re-render with customers data
setLoading(false); // Re-render with loading false
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
