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.
show more answers
Your answer