Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Data Lifecycle:
- 1. Component:
- * Dispatches action to get data
- 2. Action:
- * uses thunk to execute GQL Query with the Apollo Client object
- 3. Reducer:
- * Receives Action after thunk executed and updates store
- 4. Component:
- * update UI based on reducer state/store
- --------------------------------------------
- ## Implementation:
- Create Redux Thunk with Apollo Client as extra argument
- ```
- import ReduxThunk from 'redux-thunk'
- const client = new ApolloClient({
- reduxRootKey: 'myDifferentKey',
- });
- const store = createStore(
- combineReducers({
- todos: todoReducer,
- users: userReducer,
- myDifferentKey: client.reducer(),
- }),
- applyMiddleware(client.middleware(), ReduxThunk.withExtraArgument(client))
- );
- ```
- Create GQL operations in Folder called Request_gql.js
- ```
- import gql from 'graphql-tag';
- // let's write a function to generate our mutation params
- // in our example we'll be updating the count of a counter
- function generateMutationObject(id) {
- return {
- mutation: gql`
- mutation createCount($id: String) {
- incrementCount(id: $id)
- }`,
- variables: {
- id
- }
- };
- }
- ```
- Use these operations in dispatched actions as Thunks (mutations and queries)
- ```
- function incrementCount(id) {
- return (dispatch, getState, client) => {
- // we have access to the client inside this function
- client.mutate(generateMutationObject(id)).then((result) => {
- if (result.data) {
- // if the mutation yields data, dispatch an action with that data
- return dispatch({
- type: "UPDATE_COUNT",
- data: result.data.incrementCount
- });
- }
- });
- };
- }
- ```
- ------------------------------------------------------------
Add Comment
Please, Sign In to add comment