Estou usando o react-router-dom e o history
Rotas do index.js
const history = createBrowserHistory();
ReactDOM.render((
<Router history={history}>
<Switch>
<Route exact path="/" component={Login}/>
<Route path="/timeline" component={App}/>
</Switch>
</Router>
), document.getElementById('root'));
serviceWorker.unregister();
Metodo envia do Login.js
envia(event) {
event.preventDefault();
const requestInfo = {
method:'post',
body:JSON.stringify({login:this.login.value, senha:this.senha.value}),
header: new Headers({
'Content-type':'application/json',
})
};
fetch('https://instalura-api.herokuapp.com/api/login', requestInfo)
.then(response => {
if(response.ok){
return response.text();
} else {
throw new Error('Não foi possível fazer o login')
}
})
.then(token => {
localStorage.setItem('auth-token', token);
this.props.history.push('timeline');
})
.catch(error => this.setState({msg:error.message}))
}
Timeline.js
constructor() {
super();
this.state = {fotos: []};
}
componentDidMount() {
fetch(`https://instalura-api.herokuapp.com/api/fotos?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`)
.then(response => response.json())
.then(fotos => {
this.setState({fotos:fotos});
});
}
render() {
return (
<div className="fotos container">
{this.state.fotos.map(foto => <Foto foto={foto}/>)}
</div>
);
}