reduxql
v0.0.1-pre2
Published
Use GraphQL to select from a Redux store
Downloads
3
Readme
ReduxQL
Proof of concept for using GraphQL to select data from a Redux store.
Under active development, but definitely not ready for production!
npm i --save [email protected]
Motivation
When using Redux, it is advisable to keep your reducers as "dumb" as possible by keeping the minimum amount of state in your store.
While rendering, we then have to transform this Redux store into props for our components. You probably use a library like react-redux or reselect to accomplish this.
This library allows us to declaratively define these "selectors" as a GraphQL schema over the Redux store to provide a more robust interface for handling local data.
Example
Support we have a local Redux store that contains data for a nested TodoList:
todos: {
0: {
tag: 'Weekend picnic',
childTodoIds: ['1', '2'],
},
1: {
tag: 'Make juice',
childTodoIds: [],
},
2: {
tag: 'Cut vegetables',
childTodoIds: [],
},
rootIds: ['0'],
expandedTodoIds: ['0'],
},
We need to transform our data so that our "dumb" components can render it. Wouldn't it be great if we could just use a GraphQL query to provide the data?
1. Define a Schema
const typeDefs = [`
schema {
query: RootQuery
}
type Todo {
id: ID!
tag: String
children: [Todo]
}
type RootQuery {
todos(): [Todos]!
}
`];
const resolvers = {
RootQuery: {
todos(root, { id }, { state }) {
// ...
},
},
Todo: {
children(root, { id }, { state }) {
// ...
}
},
};
const schema = generateSchema({ typeDefs, resolvers });
2. Provide the schema to React components:
import { createStore } from 'redux';
import { Provider } from 'reduxql';
import reducer from './reducers';
import schema from './schema';
const store = createStore(reducer);
render(
<Provider schema={schema} store={store}>
<AppContainer />
</Provider>,
root,
);
3. Connect components to render data:
@connect({
mapQueryToProps() {
return {
query: `{
todos {
id
isExpanded
tag
children {
id
tag
}
}
}`,
};
}
})(TodoList)
API
<Provider store schema>
connect({[mapQueryToProps], [mapDispatchToProps]})
Contributing
We will be using this in production at AppHub! Check out the issues for some fun things to do, or email [email protected] if you love developer tools and want to work on this stuff full-time!