0

I have a class component, where I am getting data from async request in its local props. This data is in form of array, which I loop through and display some list elements. For the first time component renders, I receive empty array and then populated array from server. Next time component renders, I receive empty array again, Which means data in local props is null now, which makes sense. Any explanations how to deal with that, so I have populated array.

See code below:

const {List} = this.props; //data in local props of a component
<ListGroup>
    {
        List.map((f, index) => {
            return (
                <ListGroup.Item 
                    action
                    href="" 
                    key={f.get('ID')}
                    value = {f.get('ID')}
                    onClick={this.handleClick}
                >
                    {f.get('NAME')}
                </ListGroup.Item>
            )
        })
    }
</ListGroup> 

Then I have some button to switch back forth between two components. When I want to swtich to this list the local data in props is undefined or I get error says "TypeError: Cannot read property 'map' of undefined". Hope it is enough, not sure how I can show complete code here.

2
  • 1
    show what you have tried so far Commented Nov 14, 2019 at 12:19
  • What version of React are you using? And how are you managing state? Commented Nov 14, 2019 at 12:29

1 Answer 1

1

You can do empty check, Like list is available and list length is not zero.

 <ListGroup>
                  {List && List.length && List.map((f, index) => {
                      return (<ListGroup.Item 
                              action href="" 
                              key={f.get('ID')}
                              value = {f.get('ID')}
                              onClick={this.handleClick}
                              >
                              {f.get('NAME')}
                              </ListGroup.Item>
                              )
                  })}
                  </ListGroup> 
Sign up to request clarification or add additional context in comments.

2 Comments

Ok it makes sense to see if list is empty or not. But I want to know that data in local props i.e. List get empty, how can I deal with that?
If array is empty, what you wanted to do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.