Skip to content Skip to sidebar Skip to footer

ReactJs - How To Complete OnClick Before Download - Href

I have a simple React button component that when clicked should retrieve and download data on the client browser. The problem I am experiencing is that the download is triggered an

Solution 1:

Make sure to bind this to your functions. In your constructor you can do:

 constructor() {
    super();
    this.state = {
      users: ''
    };

    this.getUsers = this.getUsers.bind(this);
  }

or you can use the bind this function:

  getUsers = () => {
    const { userIds } = this.props;
    BatchRoleActions.getAllRoleUsers(userIds)
    .then((users) => {
      this.setState({ users: users});
      return  this.state.users; // This should be removed, you can use this.state.users throughout this component.
    });
  }

Solution 2:

Why not get the user data in the componentDidMount lifecycle method? It doesn't look like it needs to be called onClick.

{
  // ...
  componentDidMount() {
    this.getUsers();
  }
  // ...
  render() {
    return (
      <div className="roles-export-button">
        <a className="button button-default" href={this.state.users} download={'roles.csv'}>Export Csv</a>
      </div>
    )
  }
}

Solution 3:

How about handling the default "link" behaviour manually to get more control? Also you should probably try to access state after setState has been executed via its callback.

e.g.

getUsers(cb){
  const { userIds } = this.props;
  BatchRoleActions.getAllRoleUsers(userIds)
  .then((users) => {
    // note the callback of setState which is invoked
    // when this.state has been set
    this.setState({ users: users }, cb);
  });
}

const handleClick = () => {
  this.getUsers(() => {
    window.open(this.state.whatever)
  })
}

<span onClick={handleClick}>Export Csv</span>

Post a Comment for "ReactJs - How To Complete OnClick Before Download - Href"