4 ms·
I’ve seen people attempt to treat API calls like this as components and it just never quite works out well. How to populate the response to the Redux store? How
by bluedevil2k 5y ago
I’ve seen people attempt to treat API calls like this as components and it just never quite works out well. How to populate the response to the Redux store? How to treat errors? Retries? More advanced API calls that might require some data manipulation? We’ve always found a separate API layer works best and is far easier to test.
- zarathustreal 5y agoAbsolutely.. it doesn't make sense to pick a tool like React (a DOM rendering library) to solve the problem of HTTP request state management, that's just not what "component" means in the React sense.
- merb 5y agowell the problem is, that most of the time you want: 1. show that you start a http call, by showing a loading spinner and blocking a button 2. do the http call 3. show the result to the user (even errors) 4. unblock the button and hide the spinner thus most often http requests are somehow required to be dependant on your ui. libraries like redux-saga help with that.
- bluedevil2k 5y agotry { setLoading(true); const responseData = await api.some.apiCall(); updateUI(responseData); } catch (err) { showUIError(); } finally { setLoading(false); }
- merb 5y agothat was the easy part. now what do you do if two independent parts of the ui need to do something if the responseData gets updated. you either bubble downards or you need a store.
- bluedevil2k 5y agoYes, you'd probably use Redux and wrap that API call in a dispatch(). I try to stick to the design pattern of "get a response from the API call if you need the data in that function, otherwise use Redux". I've created a library that really helps with this if you're interested - https://github.com/bluedevil2k/ruffle https://github.com/bluedevil2k/ruffle
- merb 5y agoyeah your library looks good, unfortunatly we are using typescript and are a dotnet shop and we have our own stuff to create the store and built that into reactjs.net.