Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function in react component, WITHOUT event handlers or props

sorry if this question appeared somewhere else, but it's getting extremely frustrating to find answers where every question involves event handler or child element method calling.

I need to call a function when component is initialized, basically when window loads, or instantly.

On initialization I want to call a getGameMeta() to update Game state, if I'm trying to call it in jsx either I make a loop or get an error saying "Functions are not valid as a React child. This may happen if you return a Component instead of from render...."

class Game extends React.Component{
constructor(props) {
    super(props);
    this.state = {name: undefined,};
    this.getGameMeta = this.getGameMeta.bind(this);
}

getGameMeta(){
    fetch(Url).then(data => {
        console.log(data);
        this.setState({
            name: data[0].name
        });
    });
};

render(){
    return (
    <div>
        {/* {this.getGameMeta()} */} causes loop
        {/* {this.getGameMeta} */} causes error
        <p>{this.state.name}</p>
    </div>
    );
  };
};
like image 352
Efkiss Avatar asked Sep 17 '25 17:09

Efkiss


2 Answers

Using the componentDidMount hook is a great way to load data from a remote endpoint when the component is first mounted.

Example

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: undefined };
    this.getGameMeta = this.getGameMeta.bind(this);
  }

  componentDidMount() {
    this.getGameMeta();
  }

  getGameMeta() {
    fetch(Url).then(data => {
      console.log(data);
      this.setState({
        name: data[0].name
      });
    });
  }

  render() {
    return (
      <div>
        <p>{this.state.name}</p>
      </div>
    );
  }
}
like image 59
Tholle Avatar answered Sep 20 '25 05:09

Tholle


You can call it in componentDidMount. It guarantees that it will be called once and right after when component will be mounted. More over from React Docs:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

getGameMeta(){
    fetch(Url).then(data => {
        console.log(data);
        this.setState({
            name: data[0].name
        });
    });
};

componentDidMount(){ this.getGameMeta() }

So seems like this is the way you are looking for

like image 21
The Reason Avatar answered Sep 20 '25 07:09

The Reason