React Component to render children conditionally not working as I want it to

Viewed 112

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.

2 Answers

No there is not any way i think to prevent from children being evaluated but below can help you with the error:

return (
    <>
        <> ... some other stuff </>
        <StateHandler requestData={requestData}>
          <>
            <p>{user && user.name ? user.name : ""}</p>
          </>
        </StateHandler>
    </>
)

This way if user is undefined then it will skip evaluating and rendering user.name and instead would render nothing, and hence no error.

If you can use optional chaining, you could keep the simplicity of your code with a slight change.

return (
    <>
        <> ... some other stuff </>
        <StateHandler requestData={requestData}>
          <>
            <p>{user?.name}</p>
          </>
        </StateHandler>
    </>
)

If you can't use optional chaining, Sakshi's answer would be best.

Related