My understanding is there are a few ways to pass default values to a prop in React.
However, none of the ones I tried seems to mitigate my issue.
Essentially I'd like to have a default value to prevent undefined values to break the app completely.
i.e React App with useContext() hook
const context = useContext(FarmContext)
// destructuring assigment
const { fruit = 'foobar' } = context.data.farm[0] // apple
*****
<Compoment fruit={fruit} /> // apple
My problem:
If there is a mistake/typo when chaining the data above on either:
cooontext or dattta or farm[55]
The app breaks with cannot read property ________ of undefined
Therefore my destructured fruit = 'foobar' never kick is in place.
// does not work if there's a typo on object chaining
const { fruit = 'foobar' } = context.DA23ta.farm[0] // farm is undefined
*******
<Compoment fruit={fruit} /> // app breaks
Additionally, I've tried passing the default prop value approach:
// does not work if there's a typo
const { fruit } = context.DA23ta.farm[0] // farm is undefined
*******
<Compoment fruit={fruit || 'foobar'} /> // app breaks
I've also tried passing defaultProps as an alternative but I cannot mitigate this issue either.
The only scenario I got this to somewhat work is when I structure the data as:
const fruit = context.data.farm[0].fruuuit // big typo at the end here
// prop will render as 'foobar' bellow
<Compoment fruit={fruit || 'foobar'} /> // foobar
I'd like my code to have a fallback value no matter what happens to the data (typos, values that become undefined overtime).
I'd like that fallback default value to be at the destructuring assignment.
How can I add a preventive defensive strategy when if there's a typo/break anywhere (not just at the very last chained object as I show above) within:
const { fruit = 'foobar' } = contExt.dAta.farMM[0]
How could I still win on the other side and return foobar as the fruit prop and not have my entire app break because of one undefined prop?
Is this possible or doable at all? I'm open to other strategies (if there's any) that I have not shown here.