# @chipp972/redux-ajax

## Description

Redux actions, reducer and middleware to work declaratively with ajax requests in React.

## Usage

- [Setup](#Setup)
- [Hooks](#Hooks)
- [Selectors](#Selectors)
- [Testing](#Testing)
- [Changelog](#Changelog)

### Setup

First you must add the middleware in your store enhancers and add the reducer
in your root reducer:

```typescript
import { applyMiddleware, combineReducers, createStore, Middleware, Store, StoreEnhancer } from 'redux';
import { reduxAjaxMiddleware, reduxAjaxReducer, Fetch, reducerKey } from '@chipp972/redux-ajax';
import { composeWithDevTools } from 'redux-devtools-extension';

type MakeStoreOptions = { isDebug: boolean; fetchFn: Fetch };

export const appReducers = combineReducers({
  ...otherReducers,
  [reducerKey]: reduxAjaxReducer
});

const getStoreEnhancers = ({ isDebug, fetchFn }: MakeStoreOptions): StoreEnhancer => {
  const middlewares: Middleware[] = [...otherMiddlewares, reduxAjaxMiddleware({ fetchFn })];

  if (isDebug) {
    const logger = createLogger({ collapsed: true });
    return composeWithDevTools(applyMiddleware(...middlewares.concat(logger)));
  }

  return applyMiddleware(...middlewares);
};

export const makeStore = (options: MakeStoreOptions) => createStore(appReducers, getStoreEnhancers(options));
```

Notice that the fetch function is not provided and should be passed to the middleware.
It was done this way for:

- easier testing: you can just mock the fetchFn function in `makeStore` function
  to provide the response that you want in your test.
- easier enhancing: You can handle the network response before it is passed back
  to the middleware. You can handle time outs, server errors, etc.

The middleware will put in the store the returned result of the `fetchFn`
function.

The response field will be filled if the function resolve or the error field
will be used if the `fetchFn` rejects an error.

You can use the native fetch and use a polyfill if you need to support IE11 browser.
You can also use a librairy like [axios](https://www.npmjs.com/package/axios)
or [ky](https://www.npmjs.com/package/ky) or even XMLHttpRequest.

### Hooks

```typescript
import { useReduxAjax, RequestMethod } from '@chipp972/redux-ajax';

const requestContent = {
  url: '/test',
  method: RequestMethod.post,
  body: {
    test: 'test'
  }
};

const requestId = 'test';

export const TestComponent = () => {
  const { error, response, hasError, hasResponse, submitRequest, isRequestPending, resetRequest } = useReduxAjax({
    requestId
  });

  return (
    <div>
      {hasError && <div className="error">{error.message}</div>}
      {hasResponse && <div className="success">{response.value}</div>}
      {isRequestPending && <div className="loader">Fetching data...</div>}
      <button onClick={() => submitRequest({ requestContent })}>Fetch data</button>
      <button onClick={resetRequest}>Reset</button>
    </div>
  );
};
```

### Selectors

You can use the selectors directly with `react-redux` hooks:

```javascript
import { isRequestPending, RequestMethod } from '@chipp972/redux-ajax';
import { useSelector } from 'react-redux';

const requestContent = {
  url: '/test',
  method: RequestMethod.post,
  body: {
    test: 'test'
  }
};

const requestId = 'test';

export const TestComponent = () => {
  const isPending = useSelector(isRequestPending({ requestId }));

  return <div>{isPending && <div className="loader">Fetching data...</div>}</div>;
};
```

### Testing

If you created the function `makeStore` like highlighted earlier, you can test
very easily by using a mock in your tests.
I suggest you create a map where keys are your urls and the value is your
mocked response. You can then easily adapt for any test suite your responses.

```javascript
import { makeStore } from './configure-store';

export const defaultResponses = {
  '/some-url': require('./path/to/mock.json'),
  '/another-url': require('./path/to/other/mock.json')
};

// Extract webservice name from requestInfo in fetch
export const requestInfoToConfigKey = R.pipe(
  (requestInfo) => (typeof requestInfo === 'string' ? requestInfo : R.prop('url', requestInfo)),
  R.replace('/', ''),
  R.replace(/\?.+/, ''),
  R.replace('.json', ''),
  R.trim
);

export const setupTest = (overridenResponses = {}) => {
  // Merge default responses with the specific responses provided
  const webserviceResponses = {
    ...defaultResponses,
    ...overridenResponses
  };

  const store = makeStore({
    // Remove redux logger + redux devtools => useless in tests
    isDebug: false,
    // Match the url with a mocked response
    fetchFn: jest.fn(R.pipe(requestInfoToConfigKey, (key) => webserviceResponses[key]))
  });

  // Your other test setups
  return store;
};
```

Then in your tests you can write:

```javascript
import { submitRequest, RequestMethod } from '@chipp972/redux-ajax';

describe('something', () => {
  it('some test', () => {
    const store = setupTest({ '/some-url': { test: 'ok' } });
    store.dispatch(
      submitRequest({
        requestId,
        requestContent: {
          url: '/some-url',
          method: RequestMethod.get
        }
      })
    );

    // The rest of the test
  });
});
```

## Changelog

### 3.1.3

- Fix typing

### 3.1.2

- Trigger success and complete even if the request is cached

### 3.1.1

- Use ramda es5 imports

### 3.1.0

- Add `isCached` property in `submitRequest` action to avoid re-fetching if the request is already successful

### 3.0.2

- Fix submitting a request twice does not execute the ajax call twice

### 3.0.1

- Fix build to resolve JSX correctly

### 3.0.0

- Do not reset response when (re)submitting a request until the new response is received
- Add build property in package.json

### 2.1.2

- Add typing for response and error

### 2.1.1

- Fix @emotion/core injected in build files

### 2.1.0

- Expose `Success`, `Failure` and `Loading` components from the `useReduxAjax` hook
- Add `ReduxAjaxContainer` component to easily render the right component according to the status of multiple requests

### 2.0.2

- Fixed automatic reset when using `useReduxAjax` hook
