Reputation: 1
{data?.map((item, index) =>
How does the above line of code check for an empty array before mapping? I am not seeing any references for such. Any body please explain?
what does data?
do?
Reference here: https://dev.to/madara/fetching-data-with-react-hooks-and-fetch-api-beginners-guide-2ick
Upvotes: 0
Views: 3893
Reputation: 600
Adding ternary operator after data (data?) would check first that the data has a value and is not null or undefined, so it can not throw error in that case. It's a short hand for:
data ? data.map((item, index) => {}) : null
If the data has a value, it would execute map on it.
Upvotes: 0
Reputation: 635
This is a condition, it check if the data exists befor map to avoid returning the error message "data is null" or "data is undefined".
data?.map((item, index) => { ... })
is the same as
data
? data.map((item, index) => { ... })
: null
and the same as
if (data)
data.map((item, index) => { ... })
Upvotes: 1