kasia
A React Redux toolset for the WordPress API
Made with ❤ at @outlandish
{spongebob.title.rendered}!
v4 introduces breaking changes. Please read the CHANGELOG for more details.
{spongebob.title.rendered}!
✨ We welcome contributors!
🚦 Issues are triaged using a traffic light system:
small - quick tasks, great for beginner contributors
medium - tasks with increased complexity, may take some time to implement
large - big tasks that touch many parts of the library, will require commitment
Get started contributing here.
{spongebob.title.rendered}!
Get data from WordPress and into components with ease...
// e.g. Get a post by its slug@ { const post: spongebob = thispropskasia if !spongebob return <p>'Who lives in a pineapple under the sea?'</p> return <h1>spongebobtitlerendered!</h1> //=> Spongebob Squarepants! }
Features
- Declaratively connect React components to data from WordPress.
- Uses
node-wpapi
in order to facilitate complex queries. - Register and consume Custom Content Types with ease.
- All WP data is normalised at
store.wordpress
, e.g.store.wordpress.pages
. - Support for universal applications.
- Support for plugins, e.g.
wp-api-menus
.
Glossary
- Requirements
- Install
- Import
- Configure
- Usage
- Exports
- Plugins
- Universal Applications
- Contributing
- Author & License
Requirements
Kasia suits applications that are built using these technologies:
- React
- Redux
- Redux Sagas (>= 0.10.0)
- WordPress
- WP-API plugin
node-wpapi
Install
npm install kasia --save
yarn add kasia
Import
// ES2015
// CommonJSvar kasia =
Configure
Configure Kasia in three steps:
-
Initialise Kasia with an instance of
node-wpapi
. -
Spread the Kasia reducer when creating the redux root reducer.
-
Run the Kasia sagas after creating the redux-saga middleware.
A slimline example...
const WP = endpoint: 'http://wordpress/wp-json' const kasiaReducer kasiaSagas = const rootSaga = { ...kasiaSagas} const rootReducer = const sagaMiddleware = { const store = sagaMiddleware return store}
Usage
kasia(options) : Object
Configure Kasia.
- options {Object} Options object
Returns an object containing the Kasia reducer and sagas.
const kasiaReducer kasiaSagas =
The options
object accepts:
-
wpapi
{wpapi}An instance of
node-wpapi
. -
keyEntitiesBy
{String} (optional, default='id'
)Property of entities that is used to key them in the store.
One of:
'slug'
,'id'
. -
debug
{Boolean} (optional, default=false
)Log debug information to the console.
-
contentTypes
{Array} (optional)Array of custom content type definitions.
// Example custom content type definitioncontentTypes:name: 'book'plural: 'books'slug: 'books'route // optional, default="/{plural}/(?P<id>)"namespace // optional, default="wp/v2"methodName // optional, default={plural} -
plugins
{Array} (optional)Array of Kasia plugins.
// Example passing in pluginplugins:kasiaWpApiMenusPlugin route: 'menus' // with configurationkasiaWpApiMenusPlugin // without configuration
Decorators
Things to keep in mind:
- A component will make a request for data 1) when it mounts and 2) if its props change. For
connectWpPost
a change in props will trigger Kasia to try and find entity data for the new identifier in the store. If it is found, no request is made. - Content data should be parsed before being rendered as it may contain encoded HTML entities.
- In arbitrary queries with
connectWpQuery
, we suggest that you always call theembed
method on the query chain, otherwise embedded content data will be omitted from the response. - Paging data for the request made on behalf of the component is available at
this.props.kasia.query.paging
. - The examples given assume the use of decorators (sometimes called annotations). However decorator support is not necessary. See the end of each example for the alternative Higher Order Component approach.
@connectWpPost(contentType, identifier) : Component
Connect a component to a single entity in WordPress, e.g. Post, Page, or custom content type.
- contentType {String} The content type to fetch
- identifier {String|Number|Function} ID of the entity to fetch or function that derives it from
props
Returns a connected component.
Example, using identifier derived from route parameter on props
:
@ { const query page = thispropskasia if !querycomplete return <span>Loading...</span> return <h1>pagetitle</h1> } // Without decorator supportPage propsparamsslugPost
@connectWpQuery(queryFn[, shouldUpdate]) : Component
Connect a component to the result of an arbitrary WP-API query. Query is always made with ?embed
query parameter.
- queryFn {Function} Function that accepts args
wpapi
,props
,state
and should return a WP-API query - shouldUpdate {Function} Called on
componentWillReceiveProps
with argsthisProps
,nextProps
,state
Returns a connected component.
The component will request new data via queryFn
if shouldUpdate
returns true.
Entities returned from the query will be placed on this.props.kasia.entities
under the same
normalised structure as described in The Shape of Things.
Example, fetching the most recent "News" entities:
// Note the invocation of `embed` in the query chain@ { const query data: news } = thispropskasia if !querycomplete return <span>Loading...</span> return <div> <h1>Recent News Headlines</h1> Object </div> } // Without decorator support { return wpapi}Post
Exports
kasia
The Kasia configurator and preload utilities.
kasia/connect
The connect decorators.
kasia/types
The built-in WordPress content types that can be passed to connectWpPost
to define what content type
a request should be made for.
See Universal Application Utilities for more details.
Plugins
Kasia exposes a simple API for third-party plugins.
A plugin should:
-
be a function that accepts these arguments:
- WP {wpapi} An instance of
wpapi
- pluginOptions {Object} The user's options for the plugin
- kasiaOptions {Object} The user's options for Kasia
- WP {wpapi} An instance of
-
return an object containing
reducers
(Object) andsagas
(Array). -
use the
'kasia/'
action type prefix.
// Example definition returned by a plugin reducer: {} {} sagas: {}
A plugin can hook into Kasia's native action types, available at kasia/lib/constants/ActionTypes
.
All reducers for an action type are merged into a single function that calls each reducer in succession
with the state returned by the previous reducer. This means the order of plugins that touch the same
action type is important.
Available plugins:
Please create a pull request to get your own added to the list.
Universal Applications
Important...
- before calling the preloaders for SSR you must call
kasia.rewind()
- or if you call
runSagas()
from the utilities then this is done for you.
Utilities
runSagas(store, sagas) : Promise
Run a bunch of sagas against the store and wait on their completion.
- store {Object} Redux store enhanced with
runSaga
method - sagas {Array} Array of functions that accept the store state and return a saga generator
Returns a Promise resolving on completion of all the sagas.
preload(components[, renderProps][, state]) : Generator
Create a saga operation that will preload all data for any Kasia components in components
.
- components {Array} Array of components
- [renderProps] {Object} (optional) Render props object derived from the matched route
- [state] {Object} (optional) Store state
Returns a saga operation.
preloadQuery(queryFn[, renderProps][, state]) : Generator
Create a saga operation that will preload data for an arbitrary query against the WP API.
- queryFn {Function} Query function that returns
node-wpapi
query - [renderProps] {Object} (optional) Render props object
- [state] {Object} (optional) Store state
Returns a saga operation.
<KasiaConnectedComponent>.preload(renderProps[, state]) : Array<Array>
Connected components expose a static method preload
that produces an array of saga operations
to facilitate the request for entity data on the server.
- renderProps {Object} Render props object derived from the matched route
- [state] {Object} (optional) State object (default:
null
)
Returns an array of saga operations.
Saga Operation Signature
A saga operation is an array of the form:
sagaGeneratorFn action
Where:
-
sagaGenerator
Function that must be called with theaction
. -
action
action Object containing information for the saga to fetch data.
Example
A somewhat contrived example using the available preloader methods.
{ return }
Contributing
All pull requests and issues welcome!
- When submitting an issue please provide adequate steps to reproduce the problem.
- PRs must be made using the
standard
code style. - PRs must update the version of the library according to semantic versioning.
If you're not sure how to contribute, check out Kent C. Dodds' great video tutorials on egghead.io!
Author & License
kasia
was created by Outlandish and is released under the MIT license.