Dispatch a Redux action and get back a pretty JSON response

Overview

redux-cheerio

Redux middleware for Cheerio

Dispatch a Redux action and get back a pretty JSON response.

Cheerio works under the hood for parsing the HTML or XML document of HTTP requests. Cheerio uses a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient.

Installation

npm install redux-cheerio --save

Guide

Configure your store with the middleware

Insert redux-cheerio into the middleware chain like you would with any other piece of middleware.

import { createStore, applyMiddleware, combineReducers } from 'redux';
import cheerioMiddleware from 'redux-cheerio';
import reducers from './reducers';

const reducer = combineReducers(reducers);
const createStoreWithMiddleware = applyMiddleware(cheerioMiddleware)(createStore);

function configureStore(initialState) {
  return createStoreWithMiddleware(reducer, initialState);
}

const store = configureStore(initialState);

Go to the end of this readme for a full self-contained example of using redux-cheerio

Usage

Dispatch actions to your Redux store that have a type of CHEERIO_TASK and a payload consisting of a url to make the request to and a task function whose job is to parse the HTML using jQuery selectors.

To use the middleware, dispatch an action takes the following form:

const whateverNameWeLike = {
    type: 'CHEERIO_TASK',
    payload: { 
        url: // a string
        task: // a function
    }
};

#Example

Here is an example action that returns the HTML body of a response as a JSON object.

Define the first Cheerio action which makes the request

const getBodyOfHTML = {
    type: 'CHEERIO_TASK',
    payload: {  // the payload properties are customised by you 
        url: 'http://www.example.com',
        task: function yourCheerioFuncHere($){ return $('body') }
    }
};

Note that in this example we set the following custom payload properties:

A url

Where the HTTP request will be made to.

A function that allows us to use Jquery selectors such as '$(div).text()'

Under the hood our middleware takes the HTML from the response and calls the Cheerio.load function like so

let $ = cheerio.load(response)

Now we can use jQuery selectors to extract the the data we want from the HTML. This is especially useful for webscraping. We must remember to return the result of this selection.

Dispatch the first action

Lets dispatch the action to make the request and parse the response with the task function in our action.

// note that a promise is returned
store.dispatch(cheerioAction)

Now watch as redux-cheerio handles the dispatching of one further action depending on the success of the HTTP request.

redux-cheerio middleware dispatches an additional fulfilled action if the request was successful

When our task function returns something a CHEERIO_TASK_FULFILLED action will be dispatched as long as no errors have occured. The payload of this new action will consist of the thing we returned in our task function that was in the first CHEERIO_TASK action.

{
  type: 'CHEERIO_TASK_FULFILLED'
  payload: {
    'whatever was the result of our $('div').text() jquery selector'
  }
}

redux-cheerio middleware dispatches an additional rejected action if the request was not successful

If there was an error during the request such as a timeout or 404 status code then redux-cheerio middleware will dispatch a rejected action instead of a fulfilled one.

{
  type: 'CHEERIO_TASK_REJECTED'
  payload: {
    err: { // error defined here} 
  }
}

Full example

import { createStore, applyMiddleware } from 'redux';
import cheerioMiddleware from 'redux-cheerio'

// simplest reducer possible - just returns the next state
const reducer = (state, action) => state

const middleware = [cheerioMiddleware]

const store = createStore(reducer, applyMiddleware(...middleware))); 

// Create a action that follows the redux-cheerio signature
const cheerioAction = {
    type: 'CHEERIO_TASK',
    payload: {  // the payload properties are customised by you 
        url: 'http://www.example.com',
        task: function yourCheerioFuncHere($){ return $('body') }
    }
};  

// dispatch our action which returns a promise that we can chain with other logic
store.dispatch(cheerioAction).then(() => {
  console.log('request successsful')
}).catch(() => {
    console.log('request unsuccessful')
})
You might also like...
Redux - Create forms using Redux And React
Redux - Create forms using Redux And React

Exercício de fixação Vamos criar formulários utilizando Redux! \o/ Antes de inic

A lightweight state management library for react inspired by redux and react-redux

A lightweight state management library for react inspired by redux and react-redux

A Higher Order Component using react-redux to keep form state in a Redux store
A Higher Order Component using react-redux to keep form state in a Redux store

redux-form You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Redux

redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.

redux-immutable redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state. When Redux creat

A chart monitor for Redux DevTools https://www.npmjs.com/package/redux-devtools-chart-monitor
A chart monitor for Redux DevTools https://www.npmjs.com/package/redux-devtools-chart-monitor

Redux DevTools Chart Monitor This package was merged into redux-devtools monorepo. Please refer to that repository for the latest updates, issues and

Ruthlessly simple bindings to keep react-router and redux in sync

Project Deprecated This project is no longer maintained. For your Redux - Router syncing needs with React Router 4+, please see one of these librari

An i18n solution for React/Redux and React Native projects
An i18n solution for React/Redux and React Native projects

redux-react-i18n An i18n solution with plural forms support for Redux/React Workers of all countries, unite! Supported languages list with expected co

persist and rehydrate a redux store

Redux Persist Persist and rehydrate a redux store. v6 upgrade Web: no breaking changes React Native: Users must now explicitly pass their storage engi

A resizable and movable dock for Redux DevTools monitors
A resizable and movable dock for Redux DevTools monitors

Redux DevTools Dock Monitor A resizable and movable dock for Redux DevTools. Powered by React Dock. Installation npm install --save-dev redux-devtools

Owner
Tom
Lean/Haskell/Rust/Typescript
Tom
A mock store for testing Redux async action creators and middleware.

redux-mock-store A mock store for testing Redux async action creators and middleware. The mock store will create an array of dispatched actions which

Redux 2.5k Jan 1, 2023
DevTools for Redux with hot reloading, action replay, and customizable UI

Redux DevTools Developer Tools to power-up Redux development workflow or any other architecture which handles the state change (see integrations). It

Redux 13.3k Jan 1, 2023
RxJS middleware for action side effects in Redux using "Epics"

RxJS-based middleware for Redux. Compose and cancel async actions to create side effects and more. https://redux-observable.js.org Install This has pe

redux-observable 7.8k Jan 6, 2023
Helper to create less verbose action types for Redux

Action Typer Helper to create slightly less verbose redux action types. Uses ES6 Proxies! Highly Performant: Proxy is only run once at startup. Includ

Alister Norris 58 Nov 23, 2022
Redux Implementation using ReactJS and JSON placeholder API

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Siddheshwar Panda 1 Oct 26, 2021
Redux Tutorial - share my experience regarding redux, react-redux and redux-toolkit

Redux Tutorial 1. Introduction to Redux 1.1 What is Redux & why Redux? A small JS Library for managing medium/large amount of states globally in your

Anisul Islam 36 Dec 29, 2022
This is a simple react project that Stores the books, When the user enter any book with the category will be updated in the API and you can get someof books from API based on the category. 📚

Book Store React ?? This is a simple react project that Stores the books, When the user enter any book with the category will be updated in the API an

Reem janina 9 Nov 10, 2022
Normalizes nested JSON according to a schema

normalizr Install Install from the NPM repository using yarn or npm: yarn add normalizr npm install normalizr Motivation Many APIs, public or not, ret

Paul Armstrong 21k Dec 27, 2022
Skeleton React App configured with Redux store along with redux-thunk, redux persist and form validation using formik and yup

Getting Started with React-Redux App Some Configrations Needed You guys need to modify the baseUrl (path to your server) in the server.js file that is

Usama Sarfraz 11 Jul 10, 2022
A simple app for study react with redux, redux saga and typescript.

React com Redux, Redux-Saga e TypeScript. ?? Uma aplicação simple para entender o funcionamento do Redux e a melhor maneira de utiliza-lo junto com o

João Marcos Belanga 1 May 24, 2022