Mel
Mel

Reputation: 2715

React using react-hook-form - rendering output when no data is available - error map undefined

I'm trying to learn how to use react-hook-form in my app.

I have a form with a number of inputs.

I have an updateData function which is supposed to catch and store inputs, but it doesn't seem to be working. Each time I want to render the form, if I go back one step in the multi step form, it seems to throw and error if I do not reenter form inputs.

On my render page, I use:

{state.data.title}
{state.data.PreregistrationEntities.map(PreregistrationEntities => <Paragraph><Text>This will be registered with {PreregistrationEntities.label}.</Text></Paragraph>)}

TypeError: Cannot read property 'map' of undefined.

If I don't fill in the preregistration form field each time I render the form output page, it throws an error saying it cannot read map of undefined.

How do I render output if output can be found only? Id rather have a blank unfinished sentence than an error message in this circumstance?

This post suggests that a default value of nil might help. Before I go back to all my form inputs and start definining them as blanks - is there another solution?

Upvotes: 2

Views: 218

Answers (1)

ageoff
ageoff

Reputation: 2828

You can just add a check to not render if not present:

{state.data.title}
{state.data.PreregistrationEntities && state.data.PreregistrationEntities.map(PreregistrationEntities => <Paragraph><Text>This will be registered with {PreregistrationEntities.label}.</Text></Paragraph>)}

The more complete solution would be to add a message when not present

{state.data.title}
{state.data.PreregistrationEntities ?
    state.data.PreregistrationEntities.map(PreregistrationEntities => <Paragraph><Text>This will be registered with {PreregistrationEntities.label}.</Text></Paragraph>)
    : <Text>PreregistrationEntities does not exist</Text>}

Upvotes: 2

Related Questions