I have a custom React Component that I made to render loading and error states conditionally, this is the code:
const StateHandler = ({ requestData, children }) => {
return requestData.loading
? <LoadingIndicator />
: requestData.error
? <ErrorMessage />
: requestData.done && children;
};
It receives an object like this:
const requestData = {
loading: false, //or true
error: false, //or true
done: false //or true
}
It works, but it has a problem, suppose I use it from another component, like this:
return (
<>
<> ... some other stuff </>
<StateHandler requestData={requestData}>
<>
<p>{user.name}</p>
</>
</StateHandler>
</>
)
The problem is, the variable user will be undefined until its populated with data from an API, and {user.name} will throw "Cannot read property 'name' of undefined".
Is there any way to prevent the children being evaluated? Thanks in advance.