PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to redirect in axios?

 October 13, 2022     axios, reactjs     No comments   

Issue

Can I redirect in .then instead of console.log?

axios
  .post('/api/users/login', user)
  .then(res => console.log(res.data))
  .catch(err => this.setState({ errors: err.response.data }))

Is it possible and if it is how can I do it?


Solution

I would suggest that you should not perform side operations inside the actions (in this case axios call). This is because you would eventually add these calls inside redux thunk/saga or some other middleware.

The pattern which I follow is you return the promise and add the redirection logic inside your components(or containers). Following are the benefits of it:-

  1. It makes your code cleaner and avoids side affects inside your API calls.
  2. It makes easier to test your API calls using mock data.
  3. Showing alert in case the API fails without passing callback as function parameter.

Now, that being said you can use the above logic in following ways:-

// Component code

import { browserHistory } from 'react-router';

class TestContainer extends React.Component {
  auth = () => {
    login()
    .then(() => {
      browserHistory.push("/addUser");
    })
    .catch(() => {
      // Show alert to user;
    })
  }
  
  render () {
    return (
      <div>
        <button onClick={this.auth}>Auth</button>
      </div>
    );
  }
}

// Action code 

const login = () => {
  return axios
  .post('/api/users/login', user);
}


Answered By - Harkirat Saluja
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing