Initially, there is no property country in props. So, I need to show loading message if there is no country property in props, but the problem is that it's keep going to render loading element even property country does exist. So country property is appearing after sometime and hoc must to check for that. I'm not sure doing it properly.
const loadingComponent = (WrappedComponent) => {
return (props) => {
const [loading, setLoading] = useState(true);
useEffect(() => {
if (props.country) return setLoading(false);
}, [props]);
return !loading ? <WrappedComponent {...props} /> : <p>Loading ...</p>;
};
};
I'm trying to avoid using class order components. Or any alternative ways to create loading hoc? Thanks
You don't actually need a state in this case. If the prop exists render the component, if not render loading:
const loadingComponent = WrappedComponent =>
props =>
props.country ?
<WrappedComponent {...props} />
:
<p>Loading ...</p>;
I would create a more generic component, that accepts a predicate to check if loading is needed:
const loadingComponent = (predicate, WrappedComponent) =>
props =>
predicate(props) ?
<WrappedComponent {...props} />
:
<p>Loading ...</p>;
And then you can use it like this:
const Wrapped = (props => 'country' in props, ComponentX);
Or check for other things
const Wrapped = (({ a }) => a < 5, ComponentY);