Reputation: 440
In my react app, I'm often fetching data from an API, which leaves some time where my components are not able to render data. From my research, I now understand that if you pass undefined, defaultProps will be used, but if you pass null, defaultProps is ignored.
The way my code is currently structured, I have defaultProps in a component, but its parent passes null while data is loading, so I'm null checking everything anyway.
Does it make more sense to manually be passing around undefined values to trigger defaultProps (in the context of fetching data)?
Also, does this also apply to my redux selectors (mapStateToProps)?
e.g.
<Component bedrooms={bedrooms || undefined} />
Upvotes: 4
Views: 2244
Reputation: 5923
keep a prop say 'loading', of type boolean, which when true, would show a loader component and the actual component of bedrooms otherwise.
like:
<Component bedrooms={bedrooms} loading={bedrooms.length===0}/>
where
Component = ({bedrooms, loading})=> loading? <Loader/>: <div>bedrooms..</div>
also you can offload loading work to a HOC like
const withLoader = (Component)=>({loading, ...props})=>loading? <Loader/>: <Component {...props}/>
so, now
const withLoaderComponent = withLoader(Component);
usage <withLoaderComponent {...props}/>
Here Loader component can be any placeholder or a loading animation etc.
Further, with redux, we can move "loading" state to store, where, every onfetch action would set "loading" to true, and after fetchSuccess action will set it to false. Here, Loader can be a connected component also. So, Now we can have following decoupled structure.
<ConnectedLoader/><ConnectedComponent/>
where loading props of ConnectedLoader and props of ConnectedComponent, will be mapped to state of store with mapStateToProps/selectors
Upvotes: 2
Reputation: 960
Another way of doing it is to use Javascript's null check.
{this.state.bedrooms && <Component bedrooms={this.state.bedrooms} />}
Another way is
{this.state.bedrooms ? <Component bedrooms={this.state.bedrooms} /> : null}
When React sees null, it will not render anything.
Upvotes: 0