0

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?

2
  • I'd say do what works and figure out "elegance" later (unless you're doing some anti-pattern) Commented Apr 24, 2018 at 19:09
  • Thanks buddy. It is working, but doesnt look like "The right way" to avoid null pointer in this case. What can I do to make it smooth on the lifecycle of the React. I guess this is my main question. Commented Apr 24, 2018 at 19:12

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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}
    />
  }
);

Comments

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.