Reputation: 1890
I have a JS design question about how to provide a redux store to files that aren't react components. I have a typical react-redux application. Instead of calling fetch directly from my react components, I currently make all of my service calls in a centralized simple functional utility method file called fetches.js.
const mainFetch(uri, onSuccess, options) {
fetch(uri, options).then(response => {
onSuccess(response);
});
}
const export fetchDogs = (onSuccess) => {
mainFetch('/dogs', onSuccess, { method: 'GET' });
}
const export fetchCats = (onSuccess) => {
mainFetch('/cats', onSuccess, { method: 'GET' });
}
I realized that it'd be useful for my application to know exactly which of these requests we're currently waiting for. So I was thinking of adding this information to my redux state so that I could update mainFetch to look something like:
const mainFetch(uri, onSuccess, options, requestId) {
store.dispatch({type: 'STARTED_REQUEST', request: requestId);
fetch(uri, options).then(response => {
store.dispatch({type: 'FINISHED_REQUEST', request: requestId);
onSuccess(response);
});
}
But there's one problem, fetches.js has no access to the redux store. I could add a 'store' param to all of the methods in fetches.js, however I was thinking there'd be a better JS design pattern. Maybe initializing a class in App.js or something, similarly to how react-redux uses the Provider and 'connect' to provide the store to all child components. I'm new to JS so I was wondering how an experienced JS developer would solve this problem.
Upvotes: 2
Views: 609
Reputation: 735
This design is lacking a middleware to handle the promises.
The basic idea is when you dispatch a Promise, from the code where you are 'calling' these 'fetch' functions, there would be a middle ware which would take the action dispatched and dispatch other actions such as 'Started fetching' and 'fetching ended' to mark the asynchronous flow.
A good start would be this link on the official site of redux - https://redux.js.org/advanced/asyncflow
A middleware - https://github.com/pburtchaell/redux-promise-middleware
Upvotes: 2