Ao alterar os métodos like() e comenta() de FotoAtualizacao, para chamar os métodos da TimelineStore (através do this.props.like e this.props.comenta), passados por parâmetro pelo Timeline, lança esse warning de CORS e o erro "TypeError: NetworkError when attempting to fetch resource.".
Código novo:
like(event){
event.preventDefault();
this.props.like(this.props.foto.id);
}
comenta(event){
event.preventDefault();
this.props.comenta(this.props.foto.id, this.comentario.value);
}
Se eu utilizar da forma antiga, funciona normalmente, tanto o like() quando o comenta():
like(event){
event.preventDefault();
const url = `https://instalura-api.herokuapp.com/api/fotos/${this.props.foto.id}/like?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`;
fetch(url, {method: 'POST'})
.then(response => {
if(response.ok)
return response.json();
else{
// console.log('response: ', response);
throw new Error("Não foi possível realizar o like da foto");
}
})
.then(liker =>{
// console.log('liker: ', liker);
this.setState({ liked : !this.state.liked });
Pubsub.publish('atualiza-liker', {fotoId:this.props.foto.id, liker: liker});
// Pubsub.publish('atualiza-liker', {fotoId:this.props.id, liker}); shortest hand
});
}
Os métodos dentro do TimelineStore estão assim?
comenta(fotoId,textoComentario) {
const requestInfo = {
method:'POST',
body:JSON.stringify({texto:textoComentario}),
headers: new Headers({
'Content-type':'application/json'
})
};
fetch(`http://localhost:8080/api/fotos/${fotoId}/comment?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`,requestInfo)
.then(response => {
if(response.ok){
return response.json();
} else {
throw new Error("não foi possível comentar");
}
})
.then(novoComentario => {
const fotoAchada = this.fotos.find(foto => foto.id === fotoId);
fotoAchada.comentarios.push(novoComentario);
Pubsub.publish('timeline',this.fotos);
});
}
like(fotoId){
fetch(`http://localhost:8080/api/fotos/${fotoId}/like?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`,{method:'POST'})
.then(response => {
if(response.ok) {
return response.json();
} else {
throw new Error("não foi possível realizar o like da foto");
}
})
.then(liker => {
const fotoAchada = this.fotos.find(foto => foto.id === fotoId);
fotoAchada.likeada = !fotoAchada.likeada;
const possivelLiker = fotoAchada.likers.find(likerAtual => likerAtual.login === liker.login);
if(possivelLiker === undefined){
fotoAchada.likers.push(liker);
} else {
const novosLikers = fotoAchada.likers.filter(likerAtual => likerAtual.login !== liker.login);
fotoAchada.likers = novosLikers;
}
Pubsub.publish('timeline',this.fotos);
});
}