React-starter-kit: Fetch data by Redux from browser

Created on 28 Feb 2018  路  5Comments  路  Source: kriasoft/react-starter-kit

Good day! How can I use fetch in Redux action?
I use fetch from context in React component like this:

        static contextTypes = {
        fetch: PropTypes.func.isRequired,
    };
        ...
        async getData {
        const URL = '/api/search/content';
        const res = await this.context.fetch(URL);
        const {data} = await res.json();
                 ...
    }
       ...
      <button onClick={this.getData.bind(this)}/>

And now I want to do fetch in Redux action, and my question is how can I use this.context.fetch
in Redux action

Most helpful comment

I also missed pointing out the other error I was making. The return async takes in 3 parameters, the third parameter contains the fetch function. Like below.

export function xyz() { // redux action
  return async (dispatch, getState, { fetch, graphqlRequest }) => {

All 5 comments

I am facing a similar issue, in which fetch is seemingly undefined on the client. On the server, I am able to get fetch from the action like this:

export function xyz() { // redux action
  return async (dispatch, { fetch, graphqlRequest }) => {

Ok, so I had a problem in my client.js, the fetch wasn't being passed properly. I corrected it with the below code. I am using redux. Would be happy for feedback. I am still unable to understand how redux action is able to access the fetch from the store/context? Probably that is part of redux?

import 'whatwg-fetch';

// Universal HTTP client
const clientfetch = createFetch(fetch, {
  baseUrl: window.App.apiUrl,
});

// Initialize a new Redux store
// http://redux.js.org/docs/basics/UsageWithReact.html
const store = configureStore(window.App.state, {
  fetch: clientfetch,
  history,
});


const context = {
  // Enables critical path CSS rendering
  // https://github.com/kriasoft/isomorphic-style-loader
  insertCss: (...styles) => {
    // eslint-disable-next-line no-underscore-dangle
    const removeCss = styles.map(x => x._insertCss());
    return () => {
      removeCss.forEach(f => f());
    };
  },
  store,
  storeSubscription: null,
  fetch: clientfetch,
};

I also missed pointing out the other error I was making. The return async takes in 3 parameters, the third parameter contains the fetch function. Like below.

export function xyz() { // redux action
  return async (dispatch, getState, { fetch, graphqlRequest }) => {

See react-intl branch and createHelpers for redux-thunk on that branch

There is fetch helper injected to redux-thunk actions

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Bogdaan picture Bogdaan  路  3Comments

WiktorKa picture WiktorKa  路  3Comments

artkynet picture artkynet  路  4Comments

scazzy picture scazzy  路  3Comments

buildbreakdo picture buildbreakdo  路  3Comments