score:8
Accepted answer
you can return the promise from the axios request and then handle it in the calling function like
export function getnewquote(){
axios.defaults.baseurl = 'https://andruxnet-random-famous-quotes.p.mashape.com';
axios.defaults.headers.common['x-mashape-key'] = "my-api-key";
return axios.get('/?cat=famous&count=1')
}
and using it like
componentdidmount() {
getnewquote().then(res => {
this.setstate({ quote: res.data })
})
.catch(error => {
console.log(error)
});
}
handlenewquote() {
getnewquote().then(res => {
this.setstate({ quote: res.data })
})
.catch(error => {
console.log(error)
});
}
or call the getnewquote
function using the javascript .call
method and passing the reference of this
to it like
componentdidmount() {
getnewquote.call(this)
}
handlenewquote() {
getnewquote.call(this)
}
score:3
the above answer is absolutely correct, but what i want to focus is writing dry code, so this is how i do it.
import axios from 'axios';
class baseservice {
constructor() {
this.baseurl = "/api";
}
getdata(path) {
let url = `${this.baseurl}${path}`;
return axios.get(`${url}`);
}
}
export default (new baseservice()); // singleton object
this base service is now can be imported in other component or services.
import baseservice from './services/base.service.jsx';
class home extends react.component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentdidmount() {
let path = '/users';
baseservice.getdata(path)
.then(resp => {
this.setstate({data: resp.data});
}); // handle errors if needed
}
Source: stackoverflow.com
Related Query
- axios GET request function export/ import in react
- Axios is caching somehow my get user request react native
- React and Axios GET request issue with Safari on MacOs and iOs
- How to export function and import react hooks
- Axios get request returns undefined for the first time in React
- Cancel async Axios GET request - React hooks
- getting Network Error when calling axios get request in react js
- React with Redux Axios get request error issue with laravel 5.2 api server
- Axios get function returns a promise in React
- How can I make an axios get request wait before rendering my react component
- browser says " request has been blocked by CORS policy" when calling to a spring boot get method from react js using axios
- Dynamic dropdown list react axios get request
- React axios get request without resulting in infinite loop using useEffect
- react axios get request unable to pass/access response data
- react js : axios fecth data using a get request condition : i want names with those values with taken: true
- AXIOS GET request loop in react
- ERR_INSUFFICIENT_RESOURCES errors on Axios GET request In React
- Getting 415 error when trying to pass in multiple arguments to a get request in React with axios
- How to test axios get request function in jest/enzyme tests?
- Getting status code 304 on a get request with axios using react and redux
- React axios API GET request returning too many objects
- Axios React Doesn't append information Get Request
- React - get request using axios not able to setState
- How to test an async function which does an axios request to an api using JEST in a React application
- React import form: Ajax request into axios
- Axios get function sends empty request
- Cancelling Axios get request in React
- Axios giving error on get request in react js
- Making an axios get request and using React useState but when logging the data it still shows null
- axios GET request with form data in React JS
More Query from same tag
- Material UI: Select is collapsed, autoWidth not working
- React, Unable to make the row responsive using bootstrap
- Add children to React element
- Redux form: REGISTER_FIELD / UNREGISTER_FIELD get called after change or focus events
- How to switch image on scroll in React (like on Apple website)?
- React Hooks and localStorage dont set correct value
- How to change background color of a selected ItemList Material-Ui
- How to avoid bind/lambda in functional components event handlers?
- How to get the first and last visible date in React Big Calendar?
- reactjs .env add localhost:3000 to my axios path
- How does Create React App allow for Array.prototype.at() while it's not allowed by TypeScript?
- React.js key prop is not unique using uuid
- Function works but won't return HTML?
- React access state from another component
- How do I write this test for complete coverage?
- how to increase waiting timeout from 30000 ms to 60000 ms of npm installing time in ubuntu
- Use anchors with react-router
- Wrapper function for `styled`
- axios: Unhandled Rejection (TypeError): Cannot read property 'error' of undefined
- How can i use multer with react?
- I have two api call second is depend on first api call respose
- Material UI GridList drop down is too wide
- Map JSON object - ReactJS
- React : state is empty when trying to get it from child component
- go from array of objects to objects of array
- Somewhat complex React function component declaration with typescript
- React Redux showing data in table from API
- React webpack bundle not utf-8
- Trigger action of re-click/double click on first click of button
- next/image does not load images from external URL after deployment