What is the best way to deal with undefined details in response.js?

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?

+10
source share
1 answer

Typically, the approach that I like to do is to define the default details for the component that have the meaning of "empty". For example, in the context of the problem that you are describing, I would usually structure my component as follows (ES6 class style):

 class MyComponent extends React.Component { static defaultProps = { object: { key: [] } }; ... method() { // this.props.object.key is an empty array, but is overriden // with a value later after completion of the reducer // (trigerred asynchronously) this.props.object.key.map(doSomething); } } 

This is relatively clean, prevents code from being thrown at runtime, and forces you to create well-defined behaviors for semantically null, empty, or undefined input states.

+7
source

All Articles