reactjs

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


Hi all i wanna make API/Server call for retrieve the data into my react web application how to do that . and which is the best tool for make API call should i use AJAX or react fetch


Solution

  • 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:

    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://npm-compare.com/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;
    }