-1
I’m creating an application in React using the github api, it lists the repositories of a particular user, each item (each repository listed) has a Link from the React-router-gift called "Details", the link redirects to another page of my application where it has the details of the repository, I am using routes for this.
On the "details" page I have another link with React-router-gift directing to the home page, the problem is that when I go back to the home page it cleans the state, there is some way to go back to the page without doing this "reset" of the states?
I saw in some places that it should not "reset" the states, because the link with Routes does not give Reload on the page, so I think it may be some error in my logic.
My first solution was to use localStorage instead of state, but that doesn’t seem like the best solution.
Follow my index.js where I list all the repositories:
state = {
repos: [],
avatar_url:'',
totalRepos:0,
totalPages:0,
page:1
}
componentDidMount(){
this.setUserGithub();
this.loadRepos();
this.loadReposPagination();
}
setUserGithub(){
if(!localStorage.getItem('userGitHub')){
localStorage.setItem('userGitHub', 'gpontes98');
}
}
loadRepos = async () =>{
const response = await apiGitHub.get(`/${localStorage.getItem('userGitHub')}/repos`);
const avatar_url = response.data[0].owner.avatar_url;
const totalPages = Math.ceil(response.data.length / this.reposPerPage);
this.setState({totalRepos:response.data.length ,avatar_url, totalPages});
}
loadReposPagination = async(page = 1) =>{
const response = await apiGitHub.get(`/${localStorage.getItem('userGitHub')}/repos?per_page=${this.reposPerPage}&page=${page}`);
this.setState({repos:response.data, page});
}
prevPage = () =>{
const { page } = this.state;
if(page === 1) return;
this.loadReposPagination(page-1);
}
nextPage = () =>{
const { page, totalPages } = this.state;
if(page >= totalPages) return;
this.loadReposPagination(page+1);
}
The page details:
state = {
Repo: []
}
async componentDidMount(){
const { userGitHub, id } = this.props.match.params;
const response = await apiGitHub.get(`/${userGitHub}/repos`);
for(var i=0; i < response.data.length; i++){
if(response.data[i].id === parseInt(id)){
this.setState({Repo:response.data[i]});
break;
}
}
}
render(){
const { Repo } = this.state;
return(
<div className="repo-details">
<h1>{Repo.full_name}</h1>
<p>{Repo.description}</p>
<a href={Repo.html_url} target="_blank" rel="noopener noreferrer">Acessar no GitHub</a>
<Link to={'/'}> Voltar </Link>
</div>
)
}
And to Routes.js
const Routes = () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Main}/>
<Route path="/repos/:userGitHub/:id" component={Repo}/>
</Switch>
</BrowserRouter>
);
If you are doing something very strange I ask you to let me know, I’m starting now with React and it’s all very new to me yet.
Thank you,