简体   繁体   中英

state value getting lost even after storing it in localstorage [React/React-router]

I make a request to the api and in return I get "hello". I store this hello in a test_text variable and later in return I would want to redirect user to another url if test_text is not set. Else I would want to present a component.

This code is working properly UNTIL I refresh the page.

After refreshing the page, for some reason, test_text is being set back to "" (empty string) which is therefore redirecting me back to "/" url. This is confusing because using UseEffect, I am storing "hello" in localstorage and using another useEffect I am trying to get the "hello" text from localstorage. Here's the code. Please help me.

import {React,useState,useEffect} from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
import Landing from './components/landing/LandingIndex';
import Home from './components/home/HomeIndex';

function App() {

    const [test_text, setText_text] = useState('');

    useEffect(()=>{
        const data = localStorage.getItem('data');
        console.log(localStorage.getItem('data')); // hello
        if(data){
            setText_text(JSON.parse(data));
        }
    },[])

    useEffect(() => {
        fetch('/sessionDetails', {
            method: 'POST',
            cache: 'no-cache',
            headers: {
                'content_type': 'application/json',
            },
            body: JSON.stringify()
        }).then(response => {
            return response.json()
        }).then(json => {
            console.log(json.result_text) // hello
            setText_text(json.result_text);
            localStorage.setItem("data", JSON.stringify(json.result_text))
        })
    },[])


    return (
        <div className='App'>
        <Router>
            <Switch>
                <Route path = '/' exact component = {Landing}/>
                <Route  exact path = '/home'>
                {test_text === '' ? <Redirect to="/" /> : <Home />}
                </Route>
            </Switch>
        </Router>
        </div>
    );
}

export default App;

useEffect is called after the component has finished rendering: See What does useEffect do?

When your component finishes its first render:

  • the test_text is still equal to its initial state ie '' .
  • since test_text === '' , the <Redirect> is used when the JSX is rendered
  • after all the JSX has been rendered, the useEffect is called to update the test_text state

Pseudocode

In this example, it makes sense to check that localStorage.getItem('data') is falsy .

  • if false , use the <Redirect/> component
  • else use the <Home/> component.

Code

Try changing this line of code:

{test_text === '' ? <Redirect to="/" /> : <Home />}

to this:

{!localStorage.getItem('data') ? <Redirect to="/" /> : <Home />}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM