1

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?

Jurrian
  • 850
  • 6
  • 20
nkSong
  • 23
  • 5
  • Just write all common service / function into one class in one file, and export it – keikai Dec 18 '19 at 08:01
  • Thanks for your reply. But, if I write all common services & functions in "common.js", how can I change the 'App' component's state...? As I know, call the 'this.setState()' function of 'App' is only in App component class, doesn't it...? Is there a way to call the App's setState function from another function in 'common.js'? – nkSong Dec 18 '19 at 08:09

1 Answers1

2

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

Michael
  • 395
  • 1
  • 13