I have a reactJS application that downloads a report from a hardcoded URL specified in home.js. For testing purposes, I would like to make this a variable. How to do this?
Here's the method in question:
download() {
// fake server request, getting the file url as response
setTimeout(() => {
const response = {
file: "http://10.11.11.11:9080/api/export",
};
// server sent the url to the file!
// now, let's download:
window.open(response.file);
// you could also do:
// window.location.href = response.file;
}, 100);
}
Here's the full code:
import React, { Component } from 'react';
import './App.css';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';
import { Button, Container } from 'reactstrap';
import { withCookies } from 'react-cookie';
const API_HOST = process.env.REACT_APP_API_HOST || '';
class Home extends Component {
state = {
isLoading: true,
isAuthenticated: false,
user: undefined
};
constructor(props) {
super(props);
const {cookies} = props;
this.state.csrfToken = cookies.get('XSRF-TOKEN');
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
}
async componentDidMount() {
const response = await fetch(API_HOST + '/api/user', {credentials: 'include'});
const body = await response.text();
if (body === '') {
this.setState(({isAuthenticated: false}))
} else {
this.setState({isAuthenticated: true, user: JSON.parse(body)})
}
}
download() {
// fake server request, getting the file url as response
setTimeout(() => {
const response = {
file: "http://10.11.11.11:9080/api/export",
};
// server sent the url to the file!
// now, let's download:
window.open(response.file);
// you could also do:
// window.location.href = response.file;
}, 100);
}
login() {
let port = (window.location.port ? ':' + window.location.port : '');
if (port === ':3000') {
port = ':8080';
}
window.location.href = '//' + window.location.hostname + port + '/private';
}
logout() {
fetch(API_HOST + '/api/logout', {method: 'POST', credentials: 'include',
headers: {'X-XSRF-TOKEN': this.state.csrfToken}}).then(res => res.json())
.then(response => {
window.location.href = response.logoutUrl + "?id_token_hint=" +
response.idToken + "&post_logout_redirect_uri=" + window.location.origin;
});
}
render() {
const message = this.state.user ?
<h4>Welcome, {this.state.user.name}!</h4> :
<p>Please log in to manage Licenses</p>;
const button = this.state.isAuthenticated ?
<div>
<Button color="link"><Link to="/licenses">Manage Licenses</Link></Button>
<br/>
<Button color="link" onClick={this.download}>License Report</Button>
<br/>
<Button color="link" onClick={this.logout}>Logout</Button>
</div> :
<Button color="primary" onClick={this.login}>Login</Button>;
return (
<div>
<AppNavbar/>
<Container fluid>
{message}
{button}
</Container>
</div>
);
}
}
export default withCookies(Home);