'How can I use redux and graphql with apollo client in the same react app?
I'm working on a project, and I'm using apollo/client, graphql in react, and for the global state management, I have to use redux. I'm quite sure I'll have to handle more data in my project so I'll put it in my store. I'm wondering about how can I make redux actions to get data from graphql endpoint using apollo Client
the first part is my index.js where I set up the apollo client.
import React from "react";
import ReactDOM from "react-dom";
import App from './App.jsx';
import {BrowserRouter} from "react-router-dom";
import store from "./store";
import { Provider } from "react-redux";
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import {InMemoryCache} from "@apollo/client";
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache()
});
ReactDOM.render(
<React.StrictMode>
<ApolloProvider client={client}>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</ApolloProvider>
</React.StrictMode>,
document.getElementById("root")
);
I have a problem with completing the action file of redux. it didn't send data to the rest of the app.
import {
FETCH_PRODUCTS,
FETCH_PRODUCTS_FAIL,
FETCH_PRODUCTS_SUCCESS } from "../types";
import {gql} from "apollo-boost";
const getProductsQuery = gql`
{
category{
products{
name
inStock
gallery
category
prices{
currency
amount
}
}
}
}
`
const fetchProducts = () => async(dispatch) =>{
dispatch({
type: FETCH_PRODUCTS,
});
try{
//how can I get data from GRAPHQL by using apollo client
dispatch({
type:FETCH_PRODUCTS_SUCCESS,
payload:data,
});
}
catch(error){
dispatch({
type: FETCH_PRODUCTS_FAIL,
payload:error.message
});
}
}
// export default graphql(getProductsQuery);
export {fetchProducts};
Solution 1:[1]
When you are using Apollo, you really should not be taking that data and put it into Redux. You can still use Redux for other stuff, but the job of apollo is to hold that data and make it available in your components. Taking it out and putting it into Redux means you do double the work for no additional benefit, what's even worse there is a good chance you introduce lots of asynchronity between the two layers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | phry |