1

Why is my aync call fetchButtonTeams() below not being called. I am trying to print its results in console.log(this.state.data) below. Even if i call it in the render() I get infinite loops or errors. Can anyone suggest what to do?

I just want to print the results in console.log in render()

class TeamFilter extends Component {
  constructor() {
      super();
      this.state = { data: [] };
    }

    async fetchButtonTeams() {
      const response = await fetch(`/api/teams`);
      const json = await response.json();
      console.log(json)
      this.setState({ data: json });
    }

    handleTeamSelection = e => {
        this.props.setTeam(e.target.title);
        this.props.fetchTeams(e.target.title)
    };


    render() {

        let test = ['Chaos', 'High Elves', 'Orcs']

        this.fetchButtonTeams()

        console.log(this.state.data)

        return (
          <DropdownButton id="dropdown-team-button" title={this.props.team_name}>
              {test.map(cls => (
                  <div key={cls}>
                      <Dropdown.Item onClick={this.handleTeamSelection} title={cls}>{cls}</Dropdown.Item>
                  </div>
              ))}
          </DropdownButton>
        )
      }


    }

    const mapStateToProps = state => {
        return {
            team_name: state.team_name
        }
    };

const mapDispatchToProps = dispatch => {
        return {
            fetchCards: path => dispatch(fetchCards(path)),
            fetchTeams: params => dispatch(fetchTeams(params)),
            setTeam: team_name => dispatch({ type: "SET_TEAM", team_name })
        }
    };




export default connect(mapStateToProps, mapDispatchToProps)(TeamFilter)
7
  • Can you try fetchButtonTeams = async () => { and see if that works? Commented Dec 26, 2019 at 7:19
  • From where you are calling fetchButtonTeams? Commented Dec 26, 2019 at 7:20
  • I removed that code but how should i properly call it in render? Also @iRohitBhatia it did nothing. Commented Dec 26, 2019 at 7:21
  • @user3398034 Wait! Are you trying to call method declared inside the class from outside the class like you would call a function? Commented Dec 26, 2019 at 7:22
  • I am just trying to get the fetchButtonTeams() function to run inside render() and print the json results in console. Commented Dec 26, 2019 at 7:23

1 Answer 1

3

The reason you get infinite loops when you call the function on the render method is because each time the function is calling setState which in turn runs the function again and again, triggering an infinite loop.

I don't see where you are calling fetchButtonTeams() anywhere in your component, but a good idea for fetching data is putting the method inside a componentDidMount lifecycle method and console log inside the render method.You can learn more about lifecycle hooks here.

For your code:

class TeamFilter extends Component {
  constructor() {
    super();
    this.state = { data: [] };
  }

  componentDidMount() {
    this.fetchButtonTeams();
  }

  async fetchButtonTeams() {
    const response = await fetch(`/api/teams`);
    const json = await response.json();
    console.log(json);
    this.setState({ data: json });
  }

  handleTeamSelection = e => {
    this.props.setTeam(e.target.title);
    this.props.fetchTeams(e.target.title);
  };

  render() {
    let test = ["Chaos", "High Elves", "Orcs"];

    console.log(this.state.data);

    return (
      <DropdownButton id="dropdown-team-button" title={this.props.team_name}>
        {test.map(cls => (
          <div key={cls}>
            <Dropdown.Item onClick={this.handleTeamSelection} title={cls}>
              {cls}
            </Dropdown.Item>
          </div>
        ))}
      </DropdownButton>
    );
  }
}

const mapStateToProps = state => {
  return {
    team_name: state.team_name
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchCards: path => dispatch(fetchCards(path)),
    fetchTeams: params => dispatch(fetchTeams(params)),
    setTeam: team_name => dispatch({ type: "SET_TEAM", team_name })
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(TeamFilter);
Sign up to request clarification or add additional context in comments.

4 Comments

I am not calling it now since i removed that code. But how does that work?
Let me write a quick solution. Give me a sec :)
It seems to work after i added this above. 'componentDidMount(){ this.fetchButtonTeams() } '
Exactly, that's what I meant

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.