nkSong
nkSong

Reputation: 23

In react native, How to make function in Component to global?

Main javascript soure code like this,

import React from 'react'
import LoadingScreen from './components/LoadingScreen'

import './js/Login'
import './js/XHR'

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

    this.state = {
      load: false,
    }
  }

  XHRget = async parameter => {
    this.setState({ load: true });

    await XHR.send(parameter)
      .then(result => {
        this.setState({ load: false });
        console.log(result);
      });
  }

  render() {
    return (
      <View>
        <LoginScreen />
        <LoadingScreen load={this.state.load}></LoadingScreen>
      </View>
    );
  }
}

export default App

I create XHRget() in App.js for control the 'LoadingScreen' component.

XHR.js has two functions. 1) create and return XMLHttpRequest funciton called create() and 2) get data from server function called send().

And now, I want call the function XHRget() from login() in Login.js but, I don't know how to call.

How can I call the function XHRget() from another js file?

Upvotes: 1

Views: 772

Answers (1)

Michael
Michael

Reputation: 405

Create a new file with what ever name you like and put the function inside then export it.

ex.

export const XHRget = async (parent,parameter) =>
{
   parent.setState({load: true});
   await XHR.send(parameter)
         .then(result => {
             parent.setState({load: false});
             console.log(result);
             });
}

Remember to pass in this when calling it

Upvotes: 2

Related Questions