I understand vuex actions return promises, but I haven't found the ideal pattern to handle errors in vuex. My current approach is to use an error interceptor on my axios plugin, then committing the error to my vuex store.
in plugins/axios.js:
export default function({ $axios, store }) {
$axios.onError(error => {
store.dispatch('setError', error.response.data.code);
});
}
in store/index.js:
export const state = () => ({
error: null,
});
export const mutations = {
SET_ERROR(state, payload) {
state.error = payload;
},
}
export const actions = {
setError({ commit }, payload) {
commit('SET_ERROR', payload);
},
};
I would then use an error component watching the error state and show if there is an error. Thus there is really no need to catch any errors in either my action or in the component that dispatched the action. However I can't help to worry if it's bad design leaving exceptions uncaught? What issues could I encounter if I handle errors by this design? Suggestions on any better ways to do this?
I would argue that you should make the API call in the vuex action and if it fails, reject the promise with the error from the API call. I would avoid listing to all Axios errors and instead handle the error when it is returned in the promise, in my opinion, it would be easier to maintain and debug this way
For example:
getCartItems: function ({commit}, url) {
return axios.get(url).then(response => {
commit('setCartItems', response.data)
return response
}).catch(error => {
throw error
})
},
Improved above example to avoid redundant promise wrapping and use async/await for simplified code:
export const getCartItems = async ({commit}, url) => {
const response = await axios.get(url);
commit('setCartItems', response.data)
return response;
};
Related
I have created a redux that is going to request an API and if the result is 200, I want to redirect the user to another page using history.
The problem is: I don't know how to trigger this change if the action is a success.
I could redirect the user in my useCase function but I can't use history.push pathName/state argument because it only works in a React component.
So this is what I have done in my React component:
const acceptProposalHandler = () => {
store.dispatch(acceptProposal(id)).then(() => {
setTimeout(() => {
if (isAccepted) { //isAccepted is false by default but is changed to true if the
//request is 200
history.push({
pathname: urls.proposal,
state: {
starterTab: formatMessage({id: 'proposalList.tabs.negotiation'}),
},
});
}
}, 3000);
});
};
Sometimes it works but other times it wont. For some reason, .then is called even if the request fails.
I'm using setTimeOut because if I don't, it will just skip the if statement because the redux hasn't updated the state with isAccepted yet.
This is my useCase function from redux:
export const acceptProposal = (id: string) => async (
dispatch: Dispatch<any>,
getState: () => RootState,
) => {
const {auth} = getState();
const data = {
proposalId: id,
};
dispatch(actions.acceptProposal());
try {
await API.put(`/propostas/change-proposal-status/`, data, {
headers: {
version: 'v1',
'Content-Type': 'application/json',
},
});
dispatch(actions.acceptProposalSuccess());
} catch (error) {
dispatch(actions.acceptProposalFailed(error));
}
};
What I'm doing wrong? I'm using Redux with thunk but I'm not familiar with it.
".then is called even if the request fails." <- this is because acceptProposal is catching the API error and not re-throwing it. If an async function does not throw an error, it will resolve (i.e. call the .then). It can re-throw the error so callers will see an error:
export const acceptProposal = (id: string) => async (
// ... other code hidden
} catch (error) {
dispatch(actions.acceptProposalFailed(error));
// ADD: re-throw the error so the caller can use `.catch` or `try/catch`
throw error;
}
};
I'm facing a weird issue right now. I have a vuex store in my vue project which is seperated in different modules. I want to use Promise.all() to execute two independent async vuex action at once to enjoy the advantage of the first fail behavior.
store/modules/categories:
async CATEGORIES({ rootState }) {
const response = await axios.post('link_to_api', {
// some arguments for the api
arg: rootState.args
})
return response
}
store/modules/transportation:
async TRANSPORTATION({ rootState }) {
const response = await axios.post('link_to_api', {
// some arguments for the api
arg: rootState.args
})
return response
}
I know want to call those async functions in Promise.all:
store/modules/categories:
async PUT_CATEGORIES({ commit, dispatch, rootState }) {
try {
const [resCategories, resTransportation] = await Promise.all([
dispatch('CATEGORIES').catch(err => { console.log('Fehler bei Kabinenabfrage!'); throw {error: err, origin: 'kabine'}; }),
dispatch('transportation/TRANSPORTATION', {root:true}).catch(err => { console.log('Fehler bei Flugabfrage!'); throw {error: err, origin: 'flug'}; })
])
//do something after both promises resolved
} catch(error) {
// do something if one promise rejected
commit('errorlog/ERROR', 4, {root:true})
dispatch("errorlog/LOG_ERROR", {'origin': '2', 'error_code': '113', 'message': error.toString()}, {root:true})
router.push({path: '/Error'})
}
I get the following error:
This is weird because I used {root:true} and the prefix transport in dispatch to access the action of the transport module in store. This works great for the LOG_ERROR action in the errorlog module I use in the catch block.
If I copy the TRANSPORTATION action in the categories module it works great...
Has anybody faced this issue before and has an advice??
Thanks in advance!
In your case, {root:true} is passed as second argument although it should be passed as third.
- dispatch('transportation/TRANSPORTATION', {root:true})
+ dispatch('transportation/TRANSPORTATION', null, {root:true})
According to vuex's doc
To dispatch actions or commit mutations in the global namespace, pass { root: true } as the 3rd argument to dispatch and commit.
They also provide a sample code (which is further simplified here)
modules: {
foo: {
namespaced: true,
actions: {
// dispatch and commit are also localized for this module
// they will accept `root` option for the root dispatch/commit
someAction ({ dispatch, commit, getters, rootGetters }) {
dispatch('someOtherAction') // -> 'foo/someOtherAction'
dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
I have an issue where I am trying to use the Redux state to halt the execution of some polling by using the state in an if conditional. I have gone through posts of SO and blogs but none deal with my issue, unfortunately. I have checked that I am using mapStateToProps correctly, I update state immutably, and I am using Redux-Thunk for async actions. Some posts I have looked at are:
Component not receiving new props
React componentDidUpdate not receiving latest props
Redux store updates successfully, but component's mapStateToProps receiving old state
I was kindly helped with the polling methodology in this post:Incorporating async actions, promise.then() and recursive setTimeout whilst avoiding "deferred antipattern" but I wanted to use the redux-state as a single source of truth, but perhaps this is not possible in my use-case.
I have trimmed down the code for readability of the actual issue to only include relevant aspects as I have a large amount of code. I am happy to post it all but wanted to keep the question as lean as possible.
Loader.js
import { connect } from 'react-redux';
import { delay } from '../../shared/utility'
import * as actions from '../../store/actions/index';
const Loader = (props) => {
const pollDatabase = (jobId, pollFunction) => {
return delay(5000)
.then(pollFunction(jobId))
.catch(err => console.log("Failed in pollDatabase function. Error: ", err))
};
const pollUntilComplete = (jobId, pollFunction) => {
return pollDatabase(jobId, pollFunction)
.then(res => {
console.log(props.loadJobCompletionStatus) // <- always null
if (!props.loadJobCompletionStatus) { <-- This is always null which is the initial state in reducer
return pollUntilComplete(jobId, pollFunction);
}
})
.catch(err=>console.log("Failed in pollUntilComplete. Error: ", err));
};
const uploadHandler = () => {
...
const transferPromise = apiCall1() // Names changed to reduce code
.then(res=> {
return axios.post(api2url, res.data.id);
})
.then(postResponse=> {
return axios.put(api3url, file)
.then(()=>{
return instance.post(api3url, postResponse.data)
})
})
transferDataPromise.then((res) => {
return pollUntilComplete(res.data.job_id,
props.checkLoadTaskStatus)
})
.then(res => console.log("Task complete: ", res))
.catch(err => console.log("An error occurred: ", err))
}
return ( ...); //
const mapStateToProps = state => {
return {
datasets: state.datasets,
loadJobCompletionStatus: state.loadJobCompletionStatus,
loadJobErrorStatus: state.loadJobErrorStatus,
loadJobIsPolling: state.loadJobPollingFirestore
}
}
const mapDispatchToProps = dispatch => {
return {
checkLoadTaskStatus: (jobId) =>
dispatch(actions.loadTaskStatusInit(jobId))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(DataLoader);
delay.js
export const delay = (millis) => {
return new Promise((resolve) => setTimeout(resolve, millis));
}
actions.js
...
export const loadTaskStatusInit = (jobId) => {
return dispatch => {
dispatch(loadTaskStatusStart()); //
const docRef = firestore.collection('coll').doc(jobId)
return docRef.get()
.then(jobData=>{
const completionStatus = jobData.data().complete;
const errorStatus = jobData.data().error;
dispatch(loadTaskStatusSuccess(completionStatus, errorStatus))
},
error => {
dispatch(loadTaskStatusFail(error));
})
};
}
It seems that when I console log the value of props.loadJobCompletionStatus is always null, which is the initial state of in my reducer. Using Redux-dev tools I see that the state does indeed update and all actions take place as I expected.
I initially had placed the props.loadJobCompletionStatus as an argument to pollDatabase and thought I had perhaps created a closure, and so I removed the arguments in the function definition so that the function would fetch the results from the "upper" levels of scope, hoping it would fetch the latest Redux state. I am unsure as to why I am left with a stale version of the state. This causes my if statement to always execute and thus I have infinite polling of the database.
Can anybody point out what might be causing this?
Thanks
I'm pretty sure this is because you are defining a closure in a function component, and thus the closure is capturing a reference to the existing props at the time the closure was defined. See Dan Abramov's extensive post "The Complete Guide to useEffect" to better understand how closures and function components relate to each other.
As alternatives, you could move the polling logic out of the component and execute it in a thunk (where it has access to getState()), or use the useRef() hook to have a mutable value that could be accessed over time (and potentially use a useEffect() to store the latest props value in that ref after each re-render). There are probably existing hooks available that would do something similar to that useRef() approach as well.
I'm building some vuejs dashboard with vuex and axios, between others, and I've been struggling for a while on a pretty pesky problem: it seems I can't make more than one request! All subsequent calls fail with this error:
Fetching error... SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Bearer {the_entire_content_of_the_previous_api_response}' is not a valid HTTP header field value.
My store looks like that:
import axios from "axios";
const state = {
rawData1: null,
rawData2: null
};
const actions = {
FETCH_DATA1: ({ commit }) =>
{
if (!state.rawData1)
return axios.get("/api/data1")
.then((response) =>
{
commit("SET_RAW_DATA1", response.data);
});
},
FETCH_DATA2: ({ commit }) =>
{
if (!state.rawData2)
return axios.get("/api/data2")
.then((response) =>
{
commit("SET_RAW_DATA2", response.data);
});
}
};
const mutations = {
SET_RAW_DATA1: (state, data) =>
{
state.rawData1 = data;
},
SET_RAW_DATA2: (state, data) =>
{
state.rawData2 = data;
}
};
export default
{
namespaced: true,
state,
actions,
mutations
};
I don't think my API has any problem, as everything seems to work smoothly via Postman.
Maybe it's obvious for some, but I can't spot what's the matter as I'm still quite a vue noob...
Oh, and I'm handling the axios Promise like this, if this is of any interest:
this.$store.dispatch("api/FETCH_DATA1").then(() =>
{
// parsing this.$store.state.api.rawData1 with babyparse
}).catch((err) =>
{
this.errorMsg = "Fetching error... " + err;
});
After #wajisan answer, it does seem to work with "traditional" calls, but not with fetching file calls. I've tried stuff with my Echo api, to no avail... More details there: Serving files with Echo (Golang).
Any ideas, pretty please? :)
your code seems very correct, i think that your problem is from the API.
You should try with another one, just to make sure :)
Well, played a bit more with axios config and manage to make it work (finally!).
I just created a axios instance used by my store, and the weird header problem thingy disappeared! I'm not exactly sure why, but seems to be because of some things going on in the default axios config between my calls...
Even if not much has changed, the new store code:
import axios from "axios";
const state = {
rawData1: null,
rawData2: null
};
const api = axios.create({ // Yep, that's the only thing I needed...
baseURL: "/api"
});
const actions = {
FETCH_DATA1: ({ commit }) =>
{
if (!state.rawData1)
return api.get("/data1") // Little change to use the axios instance.
.then((response) =>
{
commit("SET_RAW_DATA1", response.data);
});
},
FETCH_DATA2: ({ commit }) =>
{
if (!state.rawData2)
return api.get("/data2") // And there too. Done. Finished. Peace.
.then((response) =>
{
commit("SET_RAW_DATA2", response.data);
});
}
};
const mutations = {
SET_RAW_DATA1: (state, data) =>
{
state.rawData1 = data;
},
SET_RAW_DATA2: (state, data) =>
{
state.rawData2 = data;
}
};
export default
{
namespaced: true,
state,
actions,
mutations
};
Hope that'll help someone!
I have one reducer for Clients, one other for AppToolbar and some others...
Now lets say that I created a fetch action to delete client, and if it fails I have code in the Clients reducer which should do some stuff, but also I want to display some global error in AppToolbar.
But the Clients and the AppToolbar reducers do not share the same part of the state and I cannot create a new action in the reducer.
So how am I suppose to show global error? Thanks
UPDATE 1:
I forget to mention that I use este devstack
UPDATE 2:
I marked Eric's answer as correct, but I have to say that solution which I am using in este is more like combination of Eric and Dan's answer...
You just have to find what fits you the best in your code...
If you want to have the concept of "global errors", you can create an errors reducer, which can listen for addError, removeError, etc... actions. Then, you can hook into your Redux state tree at state.errors and display them wherever appropriate.
There are a number of ways you could approach this, but the general idea is that global errors/messages would merit their own reducer to live completely separate from <Clients />/<AppToolbar />. Of course if either of these components needs access to errors you could pass errors down to them as a prop wherever needed.
Update: Code Example
Here is one example of what it might look like if you were to pass the "global errors" errors into your top level <App /> and conditionally render it (if there are errors present). Using react-redux's connect to hook up your <App /> component to some data.
// App.js
// Display "global errors" when they are present
function App({errors}) {
return (
<div>
{errors &&
<UserErrors errors={errors} />
}
<AppToolbar />
<Clients />
</div>
)
}
// Hook up App to be a container (react-redux)
export default connect(
state => ({
errors: state.errors,
})
)(App);
And as far as the action creator is concerned, it would dispatch (redux-thunk) success failure according to the response
export function fetchSomeResources() {
return dispatch => {
// Async action is starting...
dispatch({type: FETCH_RESOURCES});
someHttpClient.get('/resources')
// Async action succeeded...
.then(res => {
dispatch({type: FETCH_RESOURCES_SUCCESS, data: res.body});
})
// Async action failed...
.catch(err => {
// Dispatch specific "some resources failed" if needed...
dispatch({type: FETCH_RESOURCES_FAIL});
// Dispatch the generic "global errors" action
// This is what makes its way into state.errors
dispatch({type: ADD_ERROR, error: err});
});
};
}
While your reducer could simply manage an array of errors, adding/removing entries appropriately.
function errors(state = [], action) {
switch (action.type) {
case ADD_ERROR:
return state.concat([action.error]);
case REMOVE_ERROR:
return state.filter((error, i) => i !== action.index);
default:
return state;
}
}
Erik’s answer is correct but I would like to add that you don’t have to fire separate actions for adding errors. An alternative approach is to have a reducer that handles any action with an error field. This is a matter of personal choice and convention.
For example, from Redux real-world example that has error handling:
// Updates error message to notify about the failed fetches.
function errorMessage(state = null, action) {
const { type, error } = action
if (type === ActionTypes.RESET_ERROR_MESSAGE) {
return null
} else if (error) {
return error
}
return state
}
The approach I'm currently taking for a few specific errors (user input validation) is to have my sub-reducers throw an exception, catch it in my root reducer, and attach it to the action object. Then I have a redux-saga that inspects action objects for an error and update the state tree with error data in that case.
So:
function rootReducer(state, action) {
try {
// sub-reducer(s)
state = someOtherReducer(state,action);
} catch (e) {
action.error = e;
}
return state;
}
// and then in the saga, registered to take every action:
function *errorHandler(action) {
if (action.error) {
yield put(errorActionCreator(error));
}
}
And then adding the error to the state tree is as Erik describes.
I use it pretty sparingly, but it keeps me from having to duplicate logic which legitimately belongs in the reducer (so it can protect itself from an invalid state).
write custom Middleware to handle all the api related error. In this case your code will be more cleaner.
failure/ error actin type ACTION_ERROR
export default (state) => (next) => (action) => {
if(ACTION_ERROR.contains('_ERROR')){
// fire error action
store.dispatch(serviceError());
}
}
what I do is I centralize all error handling in the effect on a per effect basis
/**
* central error handling
*/
#Effect({dispatch: false})
httpErrors$: Observable<any> = this.actions$
.ofType(
EHitCountsActions.HitCountsError
).map(payload => payload)
.switchMap(error => {
return of(confirm(`There was an error accessing the server: ${error}`));
});
You can use axios HTTP client. It already has implemented Interceptors feature. You can intercept requests or responses before they are handled by then or catch.
https://github.com/mzabriskie/axios#interceptors
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});