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
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
Most helpful comment
I also missed pointing out the other error I was making. The
return asynctakes in 3 parameters, the third parameter contains the fetch function. Like below.