0

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?

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Try {name ? name : ""} This checks if name is null. If so, it prints "" , otherwise it prints whatever name is

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.