0

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>
)}
1

You can use with an array your data and calling .map() for displaying values. You can store those items in 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>
            )
        }
    </>
}

365体育足球滚球比分I hope this helps!

| improve this answer | |
1

365体育足球滚球比分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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.