What Is Right Way to Do API Call in React Js

what is right way to do API call in react js?

In this case, you can do ajax call inside componentDidMount, and then update state

export default class UserList extends React.Component {
constructor(props) {
super(props);

this.state = {person: []};
}

componentDidMount() {
this.UserList();
}

UserList() {
$.getJSON('https://randomuser.me/api/')
.then(({ results }) => this.setState({ person: results }));
}

render() {
const persons = this.state.person.map((item, i) => (
<div>
<h1>{ item.name.first }</h1>
<span>{ item.cell }, { item.email }</span>
</div>
));

return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">{ persons }</div>
</div>
);
}
}

correct way to call api using react

You need to invoke the API in componentWillMount or any other life cycle hooks and in your API callback use setState to ensure that the result is set to the components state variable. That way after the setState your component can access the value resolved by your API call.

NOTE: this.state.result will be null during the first render. Make sure to have a null check in the TreeMap component before accessing this.props.data.

IMP NOTE

Great suggestion from @aram90 about the setState invocation on unmounted components. To avoid this this.canSetState, instance variable is defined by me and added to prevent any possible setState invocation on unmounted components.

I used this approach just to call the API as early as possible even if it means a nanosecond. However, another approach would be to call the API in componentDidMount and then check for this._ismounted instance variable accordingly. For more on this checkout the answer here Is there a way to check if the react component is unmounted?. React docs suggests not to use isMounted().

There are many ways to achieve this but this is more React kind of way.

class ChartModal extends Component{
constructor(props){
super(props)

this.state = {
result: null
}
this.canSetState = false;
}

componentWillMount() {
this.canSetState = true;
this.callApi();
}

componentWillUnmount() {
this.canSetState = false;
}

callApi(){

fetch(someurl)
.then((result) => {

return result.json();
}).then((jsonResult) => {
this.canSetState && this.setState({result: jsonResult})
})
}

render(){
return (
<Modal
onOk={() => this.props.toggleVisibility()}
onCancel={() => this.props.toggleVisibility()}
visible={this.props.isVisible}
okText={'ok'}
cancelText={'cancel'}
confirmLoading={false}
title="Intent distribution chart"
>
<h1>HOWDY</h1>
<TreeMap
data={this.state.result}
width={400}
valueUnit={'count'}
/>
</Modal>
)
}
}

How to keep rest api calls in different file in react js

You can just move whole of this code into another component and add word export before function definition like:

export function get_all_user(){
// rest of code
}

and then you just have to import that in your components

import { get_all_user } from './path/to/file/'

so you can use them in multiple files by:

get_all_user()

Here is an example, it text.js file you have exported function, in index.js file you just use it

Where can I make API call with hooks in react?

Yes, there's a similar (but not the same!) substitute for componentDidMount with hooks, and it's the useEffect hook.

The other answers don't really answer your question about where you can make API calls. You can make API calls by using useEffect and passing in an empty array or object as the second argument as a replacement for componentDidMount(). The key here is the second argument. If you don't provide an empty array or object as the second argument, the API call will be called on every render, and it effectively becomes a componentDidUpdate.

As mentioned in the docs:

Passing in an empty array [] of inputs tells React that your effect doesn’t depend on any values from the component, so that effect would run only on mount and clean up on unmount; it won’t run on updates.

Here are some examples for scenarios where you will need to make API calls:

API Call Strictly on Mount

Try running the code below and see the result.

function User() {  const [firstName, setFirstName] = React.useState(null);  const [lastName, setLastName] = React.useState(null);    React.useEffect(() => {    fetch('https://randomuser.me/api/')      .then(results => results.json())      .then(data => {        const {name} = data.results[0];        setFirstName(name.first);        setLastName(name.last);      });  }, []); // <-- Have to pass in [] here!
return ( <div> Name: {!firstName || !lastName ? 'Loading...' : `${firstName} ${lastName}`} </div> );}
ReactDOM.render(<User />, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>

Which is the best way to make API call in react web application should i use react fetch or is there available any other best tool

React only deals with the view layer, so ideally it is not supposed to make api calls.
Hook react up with other patterns like flux or redux etc and see the magic.

There are couple of other ways to make api calls:

  • XMLHttpRequest
  • Fetch
  • Superagent

I prefer Fetch as it is designed to be more extensible and efficient

Also, you can see the comparison table below for more options:
https://npmcompare.com/compare/axios,isomorphic-fetch,mappersmith,superagent-bluebird-promise,then-request.

Updated on 13 Feb 17:

@Ramusesan : Below is my working code.

dataAction.js

import * as types from '../constants/ActionTypes';

export function loadData(data) {
return {type: types.LOAD_DATA, data};
}

export function getDataById(id) {
return {type: types.GET_DATA_BY_ID, id};
}

export function loadCompleteData() {
return function(dispatch, getState) {
return fetch("localhost:9090/data/", {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then ((response) => {
dispatch(loadProfiles(response));
})
.catch(error => console.log(error));
}
}

configure-store.js

import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers/index';

const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);

export default function configureStore(initialState) {
const store = createStoreWithMiddleware(rootReducer, initialState);
return store;
}

What is the best way to call an api more than once at the start of a project and save them inside a component in React js

Regarding my comments here's how I might approach the problem. You'll need to fetch a quote, and check that it's not already in the quotes array. If it's in there make another API call otherwise add it to the array.

When the array is full resolve the array, and add it to state.

function getQuotes() {

const endpoint = 'https://breakingbadapi.com/api/quote/random';

return new Promise(resolve => {

// Initialise quotes array
const quotes = [];

// Initialise the query count
(async function loop(count = 1) {

console.log(`Fetching quote ${count}`);

// Fetch the and parse the data
const response = await fetch(endpoint);
const data = await response.json();

// `data` is an array of one object so
// destructure it
const [obj] = data;

// Check if the quote exists in the quotes array
const found = quotes.find(quote => {
return quote.quote_id === obj.quote_id;
});

// If it's not there push in the new quote
if (!found) quotes.push(obj);

// If the quotes array is not full make
// another API call, otherwise resolve the
// quotes array. I've throttled the the API
// limit to one call per second in this example.
if (quotes.length < 6) {
setTimeout(loop, 1000, ++count);
} else {
resolve(quotes);
}

}());

});

}

// Call `getQuotes`, and display the contents
// of the array
async function main() {
const quotes = await getQuotes();
console.log(quotes);
}

main();

whats the proper way to make dependent api call in react redux

Personally I always add redux-thunk module to my projects. This module transform a simple redux action to a promise-like function. So I can concatenate multiple actions by using classic .then() sintax. Check documentation for more details.



Related Topics



Leave a reply



Submit