Reputation: 868
I'm trying to redirect to an error page I made when I catch an error from an axiosRequest. So anyway, I got a .js full of methods like this:
export const getPublication = async (id) => {
const idJSON = {"id": id,}
return await axios({
method: 'post',
url: 'users/getPublicationByID',
data: idJSON
})
.then(function (response) {
return response.data
})
.catch(function (error) {
alert("Hello: " + error); //this alert shows up correctly
this.context.history.replace('/error') //this isnt working
});
}
Then inside my .js pages I import that file and perform my requests. When I get an error I do get the alert inside the catch in the previous code but I'm not able to redirect my page. How can I do this?
Upvotes: 1
Views: 5293
Reputation: 410
You can pass this.props
to this function from component where you imported like
getPublication(id,this.props);
and your function
export const getPublication = async (id,props) => {
const idJSON = {"id": id,}
return await axios({
method: 'post',
url: 'users/getPublicationByID',
data: idJSON
})
.then(function (response) {
return response.data
})
.catch(function (error) {
alert("Hello: " + error); //this alert shows up correctly
props.history.push('/path');
});
}
Hope it will help
Upvotes: 2
Reputation: 413
export const getPublication = async (id) => {
const idJSON = {"id": id,}
return await axios({
method: 'post',
url: 'users/getPublicationByID',
data: idJSON
})
.then(function (response) {
return response.data
})
.catch(function (error) {
alert("Hello: " + error); //this alert shows up correctly
this.setstate({dataError:true})
});
}
and in render block :
render() {
if (this.state.dataError) {
// redirect to error if axios return error
return <Redirect to = {{ pathname: "/error" }} />;
}
}
Upvotes: 0
Reputation: 2440
can you try this :
.catch(function (error) {
alert("Hello: " + error);
window.location.replace("/error")
});
If you don't want to refresh you can use history.push
from react-router
Upvotes: 2
Reputation: 922
You are using an arrow function so this
in that context is a window or undefined (if you are in JS strict mode"). You will probably need to pass the history as an argument to the getPublication
function. Another solution (if you are sure that the function or class you are invoking your function on top of has valid history.replace) is to change the arrow function to regular function. In this case, this will refer to the scoped function/class.
Upvotes: 1