A
A
Alexander2019-01-23 00:47:44
React
Alexander, 2019-01-23 00:47:44

How to execute a function 1 time?

How to execute a function once?

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activeView: 'selectcountryandcity',
      fetchedUser: null,
    };
  }
  componentDidMount() {
  }

  checkUserBd = (userId) => {
    axios.get('http://localhost:8000/api/profiles/', {
      params: {
        vk_id:userId
      }
    })
    .then(function(response){
      if(response.data.length !== 0){
        this.setState({user: response.data[0]});
        console.log('user')
      } else {
        console.log('net')
      }
    }.bind(this))
  }
  render() {
    this.checkUserBd(123123);
         <Root activeView={this.state.activeView}>
          <SelectCountryAndCity 
            id="selectcountryandcity"
            token={this.state.token}
            countries={this.state.countries}
            cities={this.state.cities}
          />
        </Root>
  };
};


Now the CheckUserBd function starts calling an infinite number of times when loading the page, if I remove .bind (this) in the function, then the context is not transferred and the this.setState function is not visible.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2019-01-23
@AlexMine

Never write code/functions in render that change the setState state, because almost every setState is followed by render, and render will call setState again, and that one will render again - and so on forever, which is what happens to you. You can call checkUserBd inside componentDidMount.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question