Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react js - How to do Service layer call

Tags:

reactjs

I am trying to segregate below axios function to a separate service layer. Pls suggest how to do this in react js ?

class xxx extends Component {
constructor(props) {
    super(props)
    this.state = {
        ownerName: '',
    }
    this.handleKeyUp = this.handleKeyUp.bind(this)
}

handleKeyUp(e) {
    if (e.target.value.length > 4) {
        var self = this
        axios.get(`/https://exampleService.com/${e.target.value}`)
            .then(function (response) {
                self.setState({ownerName: response.data['name']})
            })
            .catch(function (error) {
                if (error.response) {
                    if (error.response.status === 404) {
                        self.setState({ownerName: `\u2014`})
                    }
                }
            })
    }
}

render () {
    return (
        <div>
            <Input OnKeyUp={(event) => this.handleKeyUp(event)} ></Input>
        </div>
        );
    }
}

I tried to separate like below using module.exports, but I'm unable to get the output from module component and pass it to xxx component.

module.exports = {
    axios.get ......
    .....
}
like image 949
user7700138 Avatar asked Oct 14 '17 23:10

user7700138


People also ask

Can we call ComponentDidMount?

There is no call to ComponentDidMount. It is only called once after the initial render. Let's take a look at how componentDidMount() could be called many times.

Does React use SPA?

single-spa-react is a helper library that helps implement single-spa registered application lifecycle functions (bootstrap, mount and unmount) for use with React.


2 Answers

You can create a class called Api and create a function in that class which would do the axios call. This function should accept a callback function, which you can use for setting the state in your component.

export default class Api{

    function DoAxiosCall(callback){
    axios.get(`/https://exampleService.com/${e.target.value}`)
                .then(function (response) {
                    callback(response.data['name']);
                })
                .catch(function (error) {
                    if (error.response) {
                        if (error.response.status === 404) {
                            callback(`\u2014`)
                        }
                    }
                })
    }
}

From your component, you can import the Api class, create an instance of it and then call the function which handles the axios call, passing the function that handles updating the state as the callback.

import Api from './path/to/Api';
....
class xxx extends Component {
constructor(props) {
    super(props)
    this.state = {
        ownerName: '',
    }
    this.handleKeyUp = this.handleKeyUp.bind(this)
    this.api = new Api();
}

updateState =(newOwner)=> this.setState({ownerName:newOwner})

handleKeyUp(e) {
    if (e.target.value.length > 4) {
      this.api.DoAxiosCall(this.updateState);
    }
}

render () {
    return (
        <div>
            <Input OnKeyUp={(event) => this.handleKeyUp(event)} ></Input>
        </div>
    );
}
}
like image 146
palsrealm Avatar answered Sep 27 '22 20:09

palsrealm


You can create service module like below.

// service.js

'use strict';

const axios = require('axios');

const getOwner = (url) => axios.get(url)
.then(response => response.data['name'])
.catch((error) => {
   if (error.response && error.response.status === 404) {
            return `\u2014`;
   };
});

module.exports = {
 getOwner
}

Now, you can use this getOwner function in your xxx component by requiring it.

 // xxx component

 const {getOwner} = require('path of service.js'); 
 ....
 ....
 handleKeyUp(e) {
 if (e.target.value.length > 4) {
    return getOwner(`https://exampleService.com/${e.target.value}`)
        .then(response => this.setState({ownerName: response}))
 }
} 
...
...
like image 41
user-developer Avatar answered Sep 27 '22 21:09

user-developer