0

I have a React component with an errors: {} object in the state. This object essentially mirrors the user: {} object, which gets data from a form in the component.

The error object will store any error messages that are returned from attempting to save to the data store.

For example
If the person forgets to enter field username, the response will contain an "errors" object. The actual error message will be in: errors.username.message

The component to display this error message should display if the message exists. I pass the potential error message through a prop errorText:

<Input value={ user.username } name="username" errorText={ errors.username } 
    placeholder="username"
    displayName="Database Username" type="text" onChange={ updateFormField } />

This is working, whether errors.username is actually a key in the object or not.

However, I am getting an error in my Input component because it can't find message of undefined.

I thought I could test for the key using in but was incredibly wrong about this. Here is my Input component:

export const Input = (props) => (
    <div className="form-group">
        <label htmlFor={ props.name }>{ props.displayName }</label>
            <input type={ props.type } value={ props.value } placeholder={ props.placeholder } 
                name={props.name} id={props.name} onChange={ props.onChange } className="form-control"/>

        { "errorText" in props ? "message" in props.errorText ? (
            <label className="label label-danger">{ props.errorText.message }</label>
        ) : "" : (
            ""
        )}
    </div>
);

Any suggestions?

2 Answers 2

1

You're passing errorText={ errors.username } prop to you Input component. This prop is set even if errors.username resolves to undefined. That means that your props in your Input component look like { errorText: undefined }.

Now "errorText" in props resolves to true, since there actually is such a key, but "message" in props.errorText throws an error, because props.errorText is undefined.

You can change this to smth like:

props.errorText !== undefined 
  && props.errorText.message !== undefined 
  && <label className="label label-danger">{props.errorText.message}</label>
Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly it.
0

I was able to compare to undefined

{ props.errorText !== undefined ? props.errorText.message !== undefined ? (
    <label className="label label-danger">{ props.errorText.message }</label>
) : ( "" ) : ("")}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.