0

In componentWillMount() i call fetch method to get data. But when fetch not loaded. This component was render.

How to fix it.? how to fetch loaded before render()

1 Answer 1

1

You can't. When you getting data and feeding your component generally you need to check if there is any data. If there is not, either render nothing or render something like "No data." or show a spinner there. Use componentDidMount for that.

class App extends Component {
  state = {
    data: "",
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => response.json())
        .then(json => this.setState( {data: json}));
  }

  render() {
    return (
      <div>
        { this.state.data ? <p>{this.state.data.title}</p>: "No data"}
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

my fetch function does not finish before render. how to fix it
@VõCátThư like it says in this answer, you "fix it" by making your render function work before the data is ready.

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.