onClick={} with div return with API content

Asked

Viewed 763 times

0

talk boys. I’m having a beginner problem... I’m new to reactjs and wanted to know how to do it: as soon as I click the button it returns me the data of the api inside a DIV

ex: (article, Section and etc...)

import React, { Component } from 'react';
import Api from '../API/index';

import './main.css'

class Main extends Component {

    constructor(props){
        super(props);
        this.state = {
            planets : [],
        }
    }   

    componentDidMount(){
        this.loadItens();
    }

        loadItens = async () => {
            const response = await Api.get('/planets');
            this.setState({ planets: response.data.results });
        }

render() {            
    return(    
        <div className="product-list mx-auto d-block text-center mt-5">          
              {this.state.planets.map(planetz => (
                  <article key={planetz._id} className="product-list mx-auto d-block text-center mt-5">
                      <p> Nome: {planetz.name} </p>
                      <p> Clima: {planetz.climate} </p>
                      <p> Terreno: {planetz.terrain} </p>
                      <p> População:  {planetz.population} </p>
                      <p> Participação em filmes: {planetz.films.length} </p>    

                      <button type="submit" onClick={this.loadItens}> Procurar Planetas </button>                 
                  </article>
              ))}            
        </div>
    );
};
}
export default Main;
  • John, could edit your question and clarify your problem / difficulty ?

  • yes, of course! has already been edited... thank you.

  • But aren’t you already doing it? In your onClick you invoke the function loadItens. loadItens search for data on your server, and then invoke the setState to change the state and re-render the component. It’s all right. The only problem is that you put your button inside the loop that mounts the HTML of the planets, so if you don’t have any planets on your state, you will not enter the loop and no button will be rendered.

  • @user140628 No. I called the map() parameter inside the article that returned me the api items. I wanted to know how to make sure that as soon as I clicked on this button he returned these parameters to me without having to call them in html. vlw!

  • Then I still don’t understand exactly what you’re trying to do. I understand that you are a beginner, but the terms you are using to describe this problem make no sense and this is making communication difficult. parâmetro is a value passed to a function "calling the map parameter" is a sentence that makes no sense. Another thing is that I’m not understanding is what you mean by "return these parameters without needing to call them"

  • ex: I returned inside the article <p> Name: {planetz.name} </p> I wanted as soon as I clicked on the button to return it to me without having to use that <p> Name: {planetz.name} </p> manually.

  • What do you mean by "use <p> Name: {planetz.name} </p> manually"? Sorry, but we seem to be speaking different languages.

  • You need to apologize no.. All right! "manually" don’t need to call you in article.

  • when clicking on the button wanted me to return this map() with the items contained in the api that in this case would be, planet name, climate, terrain, planet population. all this just by clicking the button.

Show 4 more comments

1 answer

0


It’s John, all right? See, you want to load the data just by clicking on the button, you put componentDidMount calling the API and then it will bring the data like this. I have a suggestion for you:

class Main extends Component {

    constructor(props){
        super(props);
        this.state = {
            planets : [],
        }
    }   
    // Não vai ter isso aqui!
    // componentDidMount(){
    //     this.loadItens();
    // }

        loadItens = async () => {
            const response = await Api.get('/planets');
            this.setState({ planets: response.data.results });
        }

render() {            
    return(    
        <div className="product-list mx-auto d-block text-center mt-5">
         <button
            type="submit"
            onClick={this.loadItens}
         >
           Procurar Planetas
         </button>          
              {this.state.planets.length
                && this.state.planets.map(planetz => (
                  <article
                   key={planetz._id}
                   className="product-list mx-auto d-block text-center mt-5"
                  >
                      <p> Nome: {planetz.name} </p>
                      <p> Clima: {planetz.climate} </p>
                      <p> Terreno: {planetz.terrain} </p>
                      <p> População:  {planetz.population} </p>
                      <p> Participação em filmes: {planetz.films.length} </p>         
                  </article>
              ))}            
        </div>
    );
};
}
export default Main;

What I did there was comment on your component <div /> to get out of the loop and available. I also put a check to run the map only if the Planets is populated. (It gave almost double meaning. hehehe).

I think it solves.

  • To consume an API is it not always necessary to have a life cycle method ? Thank you!

  • No, not necessarily, John. If opening the page requires for example to load only the planets name for a listing, then you can use the IdMout() or useEffect(() => {}, []) component that is part of the new React Hooks Api. These methods will make an initial reading in the API right after the page is loaded. In your case it was not necessary, since the communication with the API only occurs after a user interaction with the application. In your case, it is necessary to click the button first. If it is not clear, tell me that I explain better.

  • I totally get it. I just have one question about the DidMount component... with the API call with the async loadItens I made it’s already being consumed, right? this componentDidMount is just to render the API content on screen ? thank you!

  • This React lifecycle method is only executed when the page has been rendered, i.e., when it has already passed the render() method. I can’t remember in my head what all the life cycle methods are, but each one runs at a certain moment, type before loading the screen (componentWillMount), before destroying a component (componentWillUnMount).

  • To be clearer, and answering your question, it is not used to render anything on the screen. the method that renders is render().

  • Okay. Thanks for your help!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.