Flama
Flama

Reputation: 868

Redirecting when catching an error from axios request

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

Answers (4)

Nouman Janjua
Nouman Janjua

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

RezaGhahari
RezaGhahari

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

Renaldo Balaj
Renaldo Balaj

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

Wojciech Dynus
Wojciech Dynus

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

Related Questions