Sparsh
Sparsh

Reputation: 247

Redux Middleware And GraphQL

Ok, As per my understanding we use middleware in redux for all the async calls now from Apollo documentation we can directly use queries and mutation inside our component.

I personally thought that writing all the business logic in a separate place using middleware is more intuitive as it helps in keeping business logic away from UI (where the data interchange could take place using redux)

Is there any way to keep my business logic separate using redux middleware with GraphQL rather than mixing it in my UI ?

Just like fetch or axios in redux-logic's create-logger.

Upvotes: 2

Views: 2364

Answers (2)

winwiz1
winwiz1

Reputation: 3164

Is there any way to keep my business logic separate using redux middleware with GraphQL rather than mixing it in my UI ?

You can achieve it by using apollo-fetch with redux-saga which is a Redux middleware.

When there is a need to fetch data, dispatch a simple sync Redux action. It gets intercepted by redux-saga that can use Apollo to fetch the data asynchronously, can perform other async actions in response if needed and then dispatch one or several sync actions to Redux store.

The business logic can then be split between async redux-saga functions called 'sagas' that could trigger other sagas to accomodate more complex logic and finally dispatch action(s) to Redux which remains the main 'source of truth' in your application.

Upvotes: 2

Greg Brodzik
Greg Brodzik

Reputation: 1817

Given that my team is already using graph/Apollo Client, we've recently been moving away from using Redux, and rather opting for Apollo Client's built in solution to manage local state. As noted in its docs:

Apollo Client (>= 2.5) has built-in local state handling capabilities that allow you to store your local data inside the Apollo cache alongside your remote data. To access your local data, just query it with GraphQL. You can even request local and server data within the same query!

More specifically, using the @client directive, you flag that you would like to fetch the field data locally using either a client-side resolver to execute local queries or mutations, or from the cache. You can take a look at the docs here. The ability to use this single tool has simplified our local state management. More importantly, this solution could meet your request to have more seperation between UI and business logic, as that logic should largely be encapsulated in your client-side resolvers, which can handle async requests, including requests over the network.

Upvotes: 1

Related Questions