npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@chipp972/redux-ajax

v3.1.3

Published

Declarative fetch library using redux

Downloads

361

Readme

@chipp972/redux-ajax

Description

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

Usage

Setup

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

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 or ky or even XMLHttpRequest.

Hooks

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:

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.

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:

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