How can I get data from the API and then pass it to another component for react when it's fully loaded?


Manmohan Singh

I am getting data from pokeApi and passing it to another component.

componentDidMount() {
    fetch("https://pokeapi.co/api/v2/pokemon/")
    .then(resp => resp.json())
    .then(items =>{
        //console.log(items.results);
        items.results.forEach( item => {
            this.setState({pokemon:[...this.state.pokemon,item.name]})
            this.setState({url:[...this.state.url,item.url]})
 
        })});
}

 
render (){

    return (
        <div>
          
          <Fetchpokemon data={this.state}/>
         
         </div>
        )



}

When I console log into the Fetchpokemon component, the retrieved data is showing and updating. I only want to display the data once. E.g. It should fully load in App.js and then send the data to another component.

Buwanatesh

You can do something like this. Add state variable name to load and show the loader until data is loaded. Then we render the component to display the data. I also simplified the data loading logic to call setState only once.

constructor() {
  this.state = {
    // Your initial state
    loading: true,
  }
}

componentDidMount() {
  fetch("https://pokeapi.co/api/v2/pokemon/")
    .then(resp => resp.json())
    .then(items => {
      const pokemon = [];
      const url = [];
      items.results.forEach(item => {
        pokemon.push(item.name);
        url.push(item.url);
      });
      this.setState({ pokemon, url, loading: false });
     });
}

render (){
  if (loading) {
    return <Loader />;
  }
  return (
    <div>
      <Fetchpokemon data={this.state}/>
    </div>
  );
}

Related


How to pass static data from one component to another in React?

all I have a plan component where I define the plan type and then redirect to the registration component. I want to be able to display the user selected plan type in my registration component? I am trying to update the state like this: export default class Pl

How to pass data from component to another component

Igor I need help, in the last days I'm trying to pass data between components... I've followed a lot of examples on the internet, but none of these work. Most tutorials tell me to use @input and @output. I think this is the most correct way to pass data in ang

How to pass data from component to another component

Igor I need help, in the last days I'm trying to pass data between components... I've followed a lot of examples on the internet, but none of these work. Most tutorials tell me to use @input and @output. I think this is the most correct way to pass data in ang