react-apollo-hooks icon indicating copy to clipboard operation
react-apollo-hooks copied to clipboard

Use With Redux

Open andrejohansson opened this issue 6 years ago • 1 comments

Is there any usage example for this with redux?

Looking at the guide at https://dev.to/markusclaus/fetching-data-from-an-api-using-reactredux-55ao

I'm trying to get the benefits of react-apollo hooks + code generation together with redux and typescript.

More specifically, I think I want replace the part below with the useQuery section of react-apollo-hooks But since this is a function and not in a component I guess I cant use hooks?

Please note, I'm new to a lot of the concepts so I might going about this completely wrong.

// fetchProducts.js

import {fetchProductsPending, fetchProductsSuccess, fetchProductsError} from 'actions';

function fetchProducts() {
    return dispatch => {
        dispatch(fetchProductsPending());
        fetch('https://exampleapi.com/products')
        .then(res => res.json())
        .then(res => {
            if(res.error) {
                throw(res.error);
            }
            dispatch(fetchProductsSuccess(res.products);
            return res.products;
        })
        .catch(error => {
            dispatch(fetchProductsError(error));
        })
    }
}

export default fetchProducts;

I think would want something similar to:

import {
  fetchOrganizationsPending,
  fetchOrganizationsSuccess,
  fetchOrganizationsError
} from './actions';
import {ThunkAction} from "redux-thunk";
import {AppState} from "../index";
import {Action} from "redux";
import {useOrganizationsQuery} from "../../graphql/types";

const fetchOrganizations = ( ): ThunkAction<void, AppState, null, Action> => async dispatch => {
  return dispatch( () =>
  {
    const { data, error, loading } = useOrganizationsQuery();

    if (loading) {
      dispatch(fetchOrganizationsPending());
    }

    if (error) {
      dispatch(fetchOrganizationsError(error.message));
    }

    dispatch(fetchOrganizationsSuccess(data));
    return data;
  })
};

export default fetchOrganizations;

andrejohansson avatar Jul 09 '19 09:07 andrejohansson

Have you thought about using the Apollo cache instead of Redux (to keep it simple)? I think conceptually if you wanted to use Redux and the Apollo hook it would be a case of having an action creator in your component?

adriandurran avatar Jul 19 '19 18:07 adriandurran