Fernando Maymone
Fernando Maymone

Reputation: 755

React error with not fetched data. Ugly Code and null pointer. What to do?

I have an React code that needs to fetch some data from an API, put it on a redux-store, and then render a List with this data. This is what Im doing

constructor(props) {
    super(props);

    this.state = {
      isLoading: false,
    };
  }
  componentDidMount() {
    this.setState({ isLoading: true });
    this.loadData();
  }

  loadData = async () => {

    try {
       API.getList()
        .then(data => {
            this.updateState(data);
        })
        .then(data => this.setState({ isLoading: false }))
        .catch(function(error) {
          console.log(error.message);
        });
    } catch (e) {}
  };

  updateState = async (data) => {
    if (data != null) {
      await this.props.mainActions.receiveData(data);
    }
  };

  render() {
    const { isLoading  } = this.state;

    if (isLoading) {
      return <p>Loading ...</p>;
    }
    let items = [];
    if (this.props.items.data !== undefined) {
      items = this.props.items.data.stadiums;
    }
    return <MyList items={items} />;
  }
}

The problem is, the first time it renders, when I try to get "this.props.items" it is undefined yet.

So I need to put this ugly IF to dont break my code.

What will be a more elegant solution for this problem?

Upvotes: 0

Views: 48

Answers (3)

Farshad J
Farshad J

Reputation: 121

Jsx doesn't render undefined or null so you can include your condition in your return statement.

Instead of writing an if statement, do this:

return (
 {
   this.props.items.data &&
   this.props.items.data.stadiums &&
   <Mylist 
   items={this.props.items.data.stadiums}
    />
  }
);

Upvotes: 0

deowk
deowk

Reputation: 4318

I am assuming the use of ES6 here:

I would set a defaultProp for items in the MyList component

export class MyList extends Component {
    ...
    static defaultProps = {
      items: []
    }
    ...
}

This way, if you pass items as undefined and mapping over items in your render method it will produce an empty array which is valid jsx

Upvotes: 1

Fernando Maymone
Fernando Maymone

Reputation: 755

Ok. Just change the "componentDidMount" with "componentWillMount".

Upvotes: 0

Related Questions