I’m losing the state with when returning page with <Link> of the React-router-dom - REACT

Asked

Viewed 36 times

-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,

1 answer

0


If you are using the Switch in your Forums this solution will be suitable for you:

The navigation with Switch in the React-router-dom "disassembles" its component when changing route, with one exception: nested routes

If you go from "rotaum/" to "rotadois/" your component rendered in "rotaum/" will be unmounted so your States will no longer exist, when you access "rotaum/" again your component will be created and rendered from scratch.

If you go from "rotaum/" to "rotaum/rotadois" the "rotaum/" component will not be disassembled and therefore your States will continue to exist and when you return to that component will be as you left it.

Source: https://github.com/ReactTraining/react-router/issues/6804

Browser other questions tagged

You are not signed in. Login or sign up in order to post.