Over the past year+, I’ve been working in-depth with React at Automattic. I’ve also been trying to bring everything I’m learning there into WordPress themeing (since that’s a hobby of mine). Last year I posted about a simple theme, Anadama, which used the REST API plugin. With the REST API slated to be released with WordPress 4.7, I’ve been working on more theme tools for using React with the API.
One thing I noticed while working is that I was copy-pasting data-management between projects. In every project, I used React and Redux, and would have the same state tree setup, same actions, and same selectors. I tried breaking this up into the “ducks” approach, and while it still feels a little clunky, it works enough to share.
I also used an approach from Calypso, where we have Query Components to handle fetching data into the global state. They don’t do anything else – you drop a query component into a component, and you can trust that when the component renders, the fetch will happen and data will be available.
Since the Query Components use the redux “ducks”, I’ve bundled both into data-type packages. Each of these come with reducers, actions, selectors, and the query component for fetching data. Grab them off NPM by running
npm install [package] – There are packages for posts, pages, taxonomy terms, and comments:
Between this and
create-react-app, I made a super-simple “list view” of a blog in about 15 minutes. I’m also using these packages in Foxhound, which is the theme powering this site.
How can you use this yourself? Say you want to use WP posts in your project, where you are already using react & redux.
- Install the package:
npm install wordpress-query-posts --save
- Add the reducer to your state tree (code example)
- Import the
QueryPostscomponent, and drop it into the component where you need post data. (code example)
- Import the selectors, so you can pull the post data from the state in your
connected component (code example)
I hope other people find this useful, and let me know here or on github if there are any issues, or if you want to make a PR 😄
Thanks to everyone working on the REST API, and especially thanks to kadamwhite for the wpapi node library, which made my life so much simpler as I built this up!
(Note that this only works with the REST API plugin at the moment, due to this issue with the API client.)