Reputation: 403
I'm having trouble with the first render of my application. I know the issue is because initially my 'const name' is undefined. When I set it to something such as a string, the app will load, and then I can put the original code back in and the app will work like it's supposed to. But if I refresh, I get the error again. Here is my code:
const HomePage = (props) => {
const name = props.name.newMovement.movementName;
const displayMovementButtons = () => {
if (!name) {
return (
<div className={classes.noMovementsMessage} >Click add button to begin</div>
)
}
return (
<Button
className={classes.movementButtons}
onClick={() => history.push('/movement/:id')}
>
<div className={classes.movementName} >{name}</div>
</Button>
)
};
So, 'name' is what starts off as undefined. How can I restructure my code so that it will do the initial render?
Upvotes: 0
Views: 1017
Reputation: 1145
Try {name ? name : ""}
This checks if name is null. If so, it prints ""
, otherwise it prints whatever name is
Upvotes: 0
Reputation: 2783
Either props.name
or props.name.newMovement
is undefined. If you're working with async data it's likely that the name
property hasn't been set at the time of the initial render. You can try Optional chaining so that your component doesn't immediately throw an error when the name property isn't defined.
const name = props.name?.newMovement?.movementName;
Upvotes: 1