Menu

Redux Fetch Resource

FetchResource


Summary

FetchResource is an asynchronous action creator which makes a single request to the specified endpoint.


Reference

FetchResource(endpoint: string, options: ?object)



Arguments


endpoint (string)

The endpoint to make the request to.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  /**
   * Make a GET request to http://mydomain.com/things
   */
  fetchThings: () => dispatch(
    FetchResource('/things')
  )
});

@connect(null, mapDispatchToProps);
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options (object)

Options to control behaviour. All fields are optional unless stated otherwise.


options.method (string)

Sets the request method. Falls back to the defaultMethod option in middleware.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  /**
   * Make a GET request to http://mydomain.com/users
   *
   * NOTE:
   *  - The default method can be set in middleware config
   */
  fetchUsers: () => dispatch(
    FetchResource('/users')
  );

  /**
   * Make a PUT request to http://mydomain.com/users/create
   */
  createUser: () => dispatch(
    FetchResource('/users/create', { method: 'PUT' })
  );
});

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options.startType (string)

The name of an action to dispatch before the request starts.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';
import {
  FETCH_USERS_START,
  FETCH_USERS_SUCCESS,
  FETCH_USERS_ERROR } from './ActionReducer.js';

const mapDispatchToProps = dispatch => ({
  /**
   * Makes a GET request to http://mydomain.com/users and specifies secondary
   * actions to dispatch during the lifetime of the request.
   */
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      startType: FETCH_USERS_START,
      successType: FETCH_USERS_SUCCESS,
      errorType: FETCH_USERS_ERROR
    }
  ))
});

@connect(null, mapDispatchToProps)
export default MyComponent extends React.Component {
  /* Insert your magic here */
}

ActionReducer.js

export const FETCH_USERS_START = 'FETCH_USERS_START';
export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';
export const FETCH_USERS_ERROR = 'FETCH_USERS_ERROR';

export default function reducer (state = {}, action) {
  switch (action.type) {
    case FETCH_USERS_START:
      // Set a loading flag
    case FETCH_USERS_SUCCESS:
      // Add the users to state
    case FETCH_USERS_ERROR:
      // Set an error message
    default:
      return state;
  }
};


options.successType (string)

The name of an action to dispatch when the request is successful.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';
import {
  FETCH_USERS_START,
  FETCH_USERS_SUCCESS,
  FETCH_USERS_ERROR } from './ActionReducer.js';

const mapDispatchToProps = dispatch => ({
  /**
   * Makes a GET request to http://mydomain.com/users and specifies secondary
   * actions to dispatch during the lifetime of the request.
   */
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      startType: FETCH_USERS_START,
      successType: FETCH_USERS_SUCCESS,
      errorType: FETCH_USERS_ERROR
    }
  ))
});

@connect(null, mapDispatchToProps)
export default MyComponent extends React.Component {
  /* Insert your magic here */
}

ActionReducer.js

export const FETCH_USERS_START = 'FETCH_USERS_START';
export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';
export const FETCH_USERS_ERROR = 'FETCH_USERS_ERROR';

export default function reducer (state = {}, action) {
  switch (action.type) {
    case FETCH_USERS_START:
      // Set a loading flag
    case FETCH_USERS_SUCCESS:
      // Add the users to state
    case FETCH_USERS_ERROR:
      // Set an error message
    default:
      return state;
  }
};


options.errorType (string)

The name of an action to dispatch when the api call fails.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';
import {
  FETCH_USERS_START,
  FETCH_USERS_SUCCESS,
  FETCH_USERS_ERROR } from './ActionReducer.js';

const mapDispatchToProps = dispatch => ({
  /**
   * Makes a GET request to http://mydomain.com/users and specifies secondary
   * actions to dispatch during the lifetime of the request.
   */
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      startType: FETCH_USERS_START,
      successType: FETCH_USERS_SUCCESS,
      errorType: FETCH_USERS_ERROR
    }
  ))
});

@connect(null, mapDispatchToProps)
export default MyComponent extends React.Component {
  /* Insert your magic here */
}

ActionReducer.js

export const FETCH_USERS_START = 'FETCH_USERS_START';
export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';
export const FETCH_USERS_ERROR = 'FETCH_USERS_ERROR';

export default function reducer (state = {}, action) {
  switch (action.type) {
    case FETCH_USERS_START:
      // Set a loading flag
    case FETCH_USERS_SUCCESS:
      // Add the users to state
    case FETCH_USERS_ERROR:
      // Set an error message
    default:
      return state;
  }
};


options.onStart (function)

A callback function. Called before the request starts with the following parameters:

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      onStart: function (request, dispatch, getState) {
        // Do something before the request starts.
      },
      onSuccess: function (response, dispatch, getState) {
        // Do something on a successful response.
      },
      onError: function (error, dispatch, getState) {
        // Do something when the bad thing happens.
      }
    }
  ))
});

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options.onSuccess (function)

A callback function. Called when the api call is successful with the following parameters:

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      onStart: function (request, dispatch, getState) {
        // Do something before the request starts.
      },
      onSuccess: function (response, dispatch, getState) {
        // Do something on a successful response.
      },
      onError: function (error, dispatch, getState) {
        // Do something when the bad thing happens.
      }
    }
  ))
});

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options.onError (function)

A callback function. Called when a request or response error is encountered with the following parameters:

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      onStart: function (request, dispatch, getState) {
        // Do something before the request starts.
      },
      onSuccess: function (response, dispatch, getState) {
        // Do something on a successful response.
      },
      onError: function (error, dispatch, getState) {
        // Do something when the bad thing happens.
      }
    }
  ))
});

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options.headers (object|function)

A map (or function returning a map) of headers to send with requests

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'connect';
import {FetchResource} from 'redux-fetch-resource';

/**
 * NOTE:
 *  - Headers can be specified in the middleware config and will be merged.
 *  - Headers from middleware will be overridden by ones declared here.
 */

const mapDispatchToProps = dispatch => ({
  /**
   * Makes a GET request to http://mydomain.com/settings with the Authorization
   * header declared using an object.
   */
  fetchSettings: () => dispatch(FetchResource(
    '/settings',
    {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    }
  )),

  /**
   * Makes a GET request to http://mydomain.com/things with the X-Pagination-Token
   * header declared using a function which reads some state from the store.
   */
  fetchThings: () => dispatch(FetchResource(
    '/things',
    {
      headers (getState) {
        return {
          'X-Pagination-Token': getState().things.nextPageToken
        }
      }
    }
  ))
});

@connect(null, mapDispatchToProps)
export default MyComponent extends React.Component {
  /* Insert your magic here */
}


options.includeCookies (boolean|string)

Determines to cookie behaviour of the request. Cookie behaviour can be set for all requests in the middleware config. Use this option to override the default behaviour.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  /**
   * Make a GET request to http://mydomain.com/users with no cookies
   * NOTE:
   *  - This is the default behaviour
   */
  fetchUsers: () => dispatch(
    FetchResource('/users', { includeCookies: false })
  ),

  /**
   * Make a GET request to http://mydomain.com/users with cookies for this domain
   */
  fetchMessages: () => dispatch(
    FetchResource('/messages', { includeCookies: true })
  ),

  /**
   * Make a GET request to http://mydomain.com/users with cookies and cors enabled
   */
  fetchSettings: () => dispatch(
    FetchResource('/settings', { includeCookies: 'cors' })
  )
});

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options.body (object|function)

The request body, only applies to POST, PUT and PATCH requests. When body is a function it will receive getState as an argumnet

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  /**
   * Makes a PUT Request to http://mydomain.com/foo/create with a request body
   */
  onSubmitFoo: data => dispatch(FetchResource(
    '/foo/create',
    {
      method: 'PUT',
      body: data
    }
  )),

  /**
   * Makes a PUT Request to http://mydomain.com/bar/create with a request body
   * as a function which reads something from the state before sending
   */
  onSubmitBar: data => dispatch(FetchResource(
    '/bar/create',
    {
      method: 'PUT',
      body: function (getState) {
        return {
          ...data,
          otherThing: getState().thing
        }
      }
    }
  ))
})

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}


options.query (object)

An object of query parameters to serialize using querystring

Show Example

action-reducer.js

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';

const mapDispatchToProps = dispatch => ({
  /**
   * Make a GET request to http://mydomain.com/users?type=adminUser
   */  
  fetchAdmins: () => dispatch(FetchResource(
    '/users',
    {
      query: {
        type: 'adminUser'
      }
    }
  ))

  /**
   * Make a GET request to http://mydomain.com/users?type=basicUser&page=123
   * using a function to read some state to build the query
   */
  fetchUsers: () => dispatch(FetchResource(
    '/users',
    {
      query: function (getState) {
        return {
          type: 'basicUser',
          page: getState().users.page
        };
      }
    }
  ))
})

@connect(null, mapDispatchToProps)
export default MyComponent extends React.Component {
  /* Insert your magic here */
}


options.meta (any)

This gets passed along with any secondary actions dispatched by the middleware and is accessible as action.meta.

Show Example

MyComponent.jsx

import React from 'react';
import {connect} from 'react-redux';
import {FetchResource} from 'redux-fetch-resource';
import {FETCH_USERS_SUCCESS} from './ActionReducer.js';

const mapDispatchToProps = dispatch => ({
  /**
   * Make a GET request to http://mydomain.com/users and use the meta option to
   * instruct a custom store middleware to normalize the result payload.
   */
  fetchUsers: () => dispatch(
    FetchResource(
      '/users',
      {
        meta: { normalizeResult: true }
        successType: FETCH_USERS_SUCCESS
      }
    )
  )
})

@connect(null, mapDispatchToProps)
export default class MyComponent extends React.Component {
  /* Insert your magic here */
}

NormalizerMiddleware.js

export default store => next => action => {
  if (action.meta && action.meta.normalizeResult) {
    // normalize the action.payload.body
  }

  return next(action);
}


Returns


Promise

An es6 Promise object which is resolved when the request is successful and is rejected if an error is encountered