codedamn

Question mark (?) calling state properties

Asked by Luis Pedro Ferreira about a year ago

1

Data fetching in React - Challange 44

Hi. Maybe a stupid questino but I'm tryiing to understand why you used "?" (question mark) when calling the state userData properties name and age in the User.jsx file.

1 Answer

    1

    The '?' operator is called Optional Chaining, what is does is basically prevents your code from breaking in js. Before accessing the propertery it first checks whether that property exists or not.

    Example:

    const userData = fetch("/api/user-data")
    
    // In your jsx you may 
    // have something like
    <h1>{userData?.name}</h1>
    

    If userData is not fetched at the time of rendering your code will break. So to prevent that we use '?'.

    You may read about it more here.

    @th3c0d3br34ker

    Jainam Desai

    @th3c0d3br34ker

Your answer