Reputation: 13
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;
Upvotes: 1
Views: 409
Reputation: 5516
useEffect
is called after the component has finished rendering: See What does useEffect do?
When your component finishes its first render:
test_text
is still equal to its initial state i.e. ''
.test_text === ''
, the <Redirect>
is used when the JSX is rendereduseEffect
is called to update the test_text
statePseudocode
In this example, it makes sense to check that localStorage.getItem('data')
is falsy.
false
, use the <Redirect/>
component<Home/>
component.Code
Try changing this line of code:
{test_text === '' ? <Redirect to="/" /> : <Home />}
to this:
{!localStorage.getItem('data') ? <Redirect to="/" /> : <Home />}
Upvotes: 1