I'm building a single-page application with react and redux. Which of course needs a backend for its data. Now we're looking at what api architecture would be best, but it I couldn't find any consensus on which api architecture would best fit a react/redux application.
Now I know that you can basically consume data any way you like. But still there are clear market leaders, like redux over mobx for example. That doesn't make them better, but it's nice to at least know where the preference lies.
So my question is: which api architecture is used most for a react/redux app at this point in time?
From our experience, it's best not to make the API "fit" react/redux and vice versa. Just use thunk-action-creators and handle the API calls in whatever shape or form they are.
Here is a contrived example:
export function getUserById (userId) {
return async dispatch => {
dispatch({ type: 'REQUEST_USER_BY_ID', payload: userId })
try {
const user = await api.get(`/users/${userId}`)
ga('send', 'event', 'user', 'profile', 'view')
dispatch({
type: 'LOAD_USER',
payload: user
})
dispatch({
type: 'NOTIFY_SUCCESS',
payload: `Loaded ${user.firstname} ${user.lastname}!`
})
}
catch (err) {
dispatch({
type: 'NOTIFY_ERROR',
payload: `Failed to load user: ${err.message}`,
})
}
}
}
The biggest benefit of this approach is flexibility. The API(s) stay completely unopinionated about the consumer. You can handle errors, add retry logic, fallback logic differently on any page. Easy to glue together actions that require calls to several different apis in parallel or sequential.
We tried many approaches like "redux over the wire" and relays/apollos "bind component to query". This one stuck as the most flexible and easiest to understand and refactor.