Reputation: 318
I'm trying to add a loading icon for each card while the data is fetching from the API. Is there another way to keep this DRY? ... to avoid repeating myself?
{isLoading ? (<Loader />) : (
<div className="module card">{sales_numbers}</div>
)}
{isLoading ? (<Loader />) : (
<div className="module card">{accounts_numbers}</div>
)}
{isLoading ? (<Loader />) : (
<div className="module card">{users_numbers}</div>
)}
Upvotes: 0
Views: 1839
Reputation: 15176
You can use with an array your data and calling .map()
for displaying values. You can store those items in useState()
hook for function component or this.state
in a class component.
Try the following if you have a function component:
const [values] = useState([sales_numbers, account_numbers, users_numbers]);
return <>
{
values.map(e => isLoading ?
<Loader /> :
<div className="module card">{e}</div>
)
}
</>
In class component you need to store within this.state
like this:
constructor(props) {
super(props);
this.state = {
values: [sales_numbers, account_numbers, users_numbers]
}
}
render() {
return <>
{
this.state.values.map(e => isLoading ?
<Loader /> :
<div className="module card">{e}</div>
)
}
</>
}
I hope this helps!
Upvotes: 1
Reputation: 385
Try building a component that manage loading state by itself. This way you can have something like
export default ({data}) => (
data ? <div className="module card">{data}</div> : <Loader />
)
Your only concern is to pass data prop for each entity.
Upvotes: 1