0.1.9 • Published 5 years ago

@cweise/redux-graphql v0.1.9

Weekly downloads
11
License
ISC
Repository
github
Last release
5 years ago

Installation

npm i @cweise/redux-graphql graphql-tag redux-thunk

Usage

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import gql from "graphql-tag";
import { request, select } from "@cweise/redux-graphql";

export const query = gql`
  query {
    continents {
      name
      code
    }
  }
`;

const MyComponent = () => {
  const dispatch = useDispatch();
  const { data, isFetching } = useSelector(select(query));

  useEffect(() => {
    dispatch(request(query));
  }, []);

  if (isFetching) {
    return "is fetching";
  }

  if (!data) {
    return null;
  }

  return (
    <ul>
      {data.continents.map(continent => (
        <li>{continent.name}</li>
      ))}
    </ul>
  );
};

API

NameTypeDescription
createReducer(options)functionCreate graphql reducer with at least url property
request(gql)functionRedux action to receive remote data
select(gql)functionRedux selector to select data from state.

createReducer() Options

OptionTypeDescription
url *stringA url that point to your graphql backend
urlAliasesObjectIf you have multiple graphql endpoints, you can add each of them here
tokenPathstringIf you have an auth header already stored in your redux store you can connect it here

* required


Setup

Redux store

import { createStore, applyMiddleware, combineReducers } from "redux";
import thunk from "redux-thunk";
import { createReducer } from "@cweise/redux-graphql";

const reducer = combineReducers({
  graphql: createReducer({ url: "https://countries.trevorblades.com" })
});

const store = createStore(reducer, applyMiddleware(thunk));

export default store;

Dispatching and selecting

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import gql from "graphql-tag";
import { request, select } from "@cweise/redux-graphql";

export const query = gql`
  query {
    continents {
      name
      code
    }
  }
`;

const MyComponent = () => {
  const dispatch = useDispatch();
  const { data, isFetching } = useSelector(select(query));

  useEffect(() => {
    dispatch(request(query));
  }, []);

  if (isFetching) {
    return "is fetching";
  }

  if (!data) {
    return null;
  }

  return (
    <ul>
      {data.continents.map(continent => (
        <li>{continent.name}</li>
      ))}
    </ul>
  );
};
0.1.8

5 years ago

0.1.9

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago