tyrone 251
tyrone 251

Reputation: 339

React: Async function not being called

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)

Upvotes: 1

Views: 831

Answers (1)

Jose Felix
Jose Felix

Reputation: 1000

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

Upvotes: 3

Related Questions