Estou fazendo um projeto do FreeCodeCamp usando ReactJS. Ele consiste em fazer dois Leaderboards: um dos campers com maior pontuação nos últimos 30 dias e outro dos que acumularam mais pontos, onde no site será exibido um deles por vez, o usuário pode escolher qual leaderboard deseja ver no momento. Fiz a troca ser possível por meio do clique no elemento de título da tabela. Porém, estou enfrentando problemas devido o setState()
ser assíncrono.
Atualmente é necessário clicar 2x para que a tabela mude, ao invés de uma só. Usei alguns consoles.log
pra depurar e acredito que o método que criei para gerenciar o fetch getFetch()
esteja sendo executado antes do estado ser alterado.
E gostaria de saber, se é possível garantir que o método getFetch()
só seja executado após o setState
ser concluído?
Já tentei usar async/await e callback, mas não funcionou. Além disso já busquei por soluções na documentação e em outros sites, mas nenhuma sugerida deu certo (ou foi eu que não consegui implementar).
Segue o trecho de código onde o state é alterado e o link do preview
const allTimeApi ='https://fcctop100.herokuapp.com/api/fccusers/top/alltime'
const recentApi = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent'
class TableContent extends React.Component{
constructor(props){
super(props)
this.state = {
allTimeRequested:false,
usersData:[],
}};
getFetch(){
fetch(this.state.allTimeRequested? allTimeApi : recentApi)
.then(results => results.json())
.then(data => {
let tableData = data.map((user,index)=>(
<tr key={user.username} style={{textAlign: 'center'}}>
<th>{index+1}</th>
<td>
<img
src={user.img}
className="profilePhotos"
alt={`${user.username} profile photo`}/>
<a
href={`https://www.freecodecamp.com/${user.username}`}>
{user.username}</a>
</td>
<td>{user.recent}</td>
<td>{user.alltime}</td>
</tr>
))
this.setState({
usersData: tableData,
})
})
}
/*Gostaria de fazer o getFetch ser exec após o setState nos dois métodos abaixo*/
showBestRecent = () => {
this.setState({allTimeRequested:false})
this.getFetch()
}
showBestAllTime = () => {
this.setState({allTimeRequested:true})
this.getFetch()
}
componentDidMount(){
this.getFetch()
}
render(){
return(
<div className="col-12" style={{textAlign: 'center'}}>
<table className="table table-striped table-bordered tableShadow">
<th>#</th>
<th>Camper name</th>
<th
className={this.state.allTimeRequested?
"notSelected":"selected grad"}
onClick={this.showBestRecent}>Points in past 30 days</th>
<th
className={this.state.allTimeRequested?
"selected grad":"notSelected"}
onClick={this.showBestAllTime}>All time points</th>
<tbody>
{this.state.usersData}
</tbody>
</table>
</div>
)}
}
Soluções Tentadas:
Async/await:
Ao fazer isso, nada é renderizado na tela, tentei de duas formas
forma 1:
showBestRecent = async () => {
await this.setState({allTimeRequested:false})
this.getFetch()
}
forma 2:
showBestRecent = async () => {
await this.setState({allTimeRequested:false})
.then(this.getFetch())
}
callback:
Ao fazer isso, o state muda (percebo por causa da mudança de style no elemento do header da tabela) mas é como se a função getFetch não fosse executada (a tabela não muda)
showBestRecent = () => {
this.setState({allTimeRequested:false}),
() => this.getFetch()
}
Se cometi algum erro grotesco, peço desculpas. Ainda sou iniciante em JS e React