The Creative Network Session 6 — integrating GraphQL in React with Lokka

Previous sessions

Last night we worked on integrating GraphQL in our React client app so we can fetch data from server. This is an interesting session because we struggled quite a bit in our attempt in finding the right client side library to query GraphQL. With the help of one of our viewer binaryslothtree we finally landed on a nice tool called Lokka which is a simple and non-opinionated tool that allow us to query GraphQL server with ease.

Code from last night and video are here.

During our last session, we setup the V1 of data schema on the server side that supplies data to our home page. Now we wanted to fetch this data from our react/redux client application. Using an library to query a GraphQL is not really required, but we thought there must be some tools that simplifies this flow. Our first pick is Appollo Client. Apollo is really rich in features but soon we realized a fundamental problem with Apollo’s approach: it is very opinionated on how to architecture our client app and the action of fetching data from GraphQL server is tightly coupled with a specific component. See example below:

export default graphql(gql`

query TodoAppQuery {

todos {

id

text

}

}

`)(TodoApp);

graphql() this the core function from Apollo that makes the call to GraphQL server and fetches the data. As you can see, you have to pass in an component in the argument for this to work(in this case TodoApp is the component). We really didn’t like this approach. We ONLY want to query the server, get response and save the response data in our redux state . We should be able to have full control of how to pass that data to different components. This is where Lokka come in handy. It’s so simple and does exactly what we wanted to do:

import { Lokka } from 'lokka';

import { Transport } from 'lokka-transport-http';

import { FETCH_ALL_TOPICS } from '../../../ActionTypes';



const client = new Lokka({

transport: new Transport('/graphql')

});



export function getTopics() {

return function (dispatch) {

client.query(`

{

allTopics {

id

title

description

thumbnail

tags {

id

name

}

}

}

`).then(result => {

dispatch({

type: FETCH_ALL_TOPICS,

topics: result.allTopics,

});

});

};

}

That’s it! Here client is the tooling from Lokka and it does a simple job: it query our GraphQL server and returns the API response. We are free to interact and dispatch that response however we see fit. It only takes about 7 lines of code to set up and 5 minutes to get it running. It just works.

Once Lokka is working everything went smooth. We just needed to create the relevant reducers and dispatch API results to the redux state, and then mount the data to any component that needs to consume the data.

Hope this helps! We think Lokka is really worth a try for simple GraphQL application such as ours.