Suppose I have an action that is sent when the page loads, for example, in the index.js file.
example
store.dispatch(loadData());
in my reducer, I initialize the state for the object. Something like that
function myReducer(state = {}, action)
now I have some kind of smart component that subscribes to my state and then passes it to another component to display the data. Another important note for this scenario is the fact that data is received asynchronously. Suppose also that the key to this object is some array. So the markup component will have something like this
{this.props.object.key.map(k => do something)}
Now, since the key is not defined, if I call a card on it, I explode. The way I dealt with this is to use a simple if check. If the key is defined, run .map otherwise return zero. Then, when my data returns from the server, the rendering will be called again due to a change in the state this component is subscribed to. At this point, a key is defined and a card can be called.
Another approach is to determine how your condition will look in the gearbox. In other words, if I know that my state will be an object with an array property, I could do something like this.
const initialState = { key:[] } function myReducer(state = initialState, action)
This will help me that now I don’t need to check if the key is never defined.
My questions are; which of these approaches is better than the other? Or maybe there is another way to completely handle this?