if function is not up to date react - javascript

I'm new in this amazing site, I'm just having a problem in my react app.
this is the index.js I'm using react-router-dom in this page I just need to show this.state.show for who is in a home page, So in the login.js request I've created 'loginToken' with this code sessionStorage.setItem('loginToken', 'Value')
and now I'm making a verification for sessionStorage.getItem('loginToken') in index.js
Everything works fine but my problem is when I'm in a home page this text 'Welcome Back' doesn't appears automatically I need to refresh the home page to see it. I don't know why this happening.
Is it because I'm using componentWillMount?
I've tried to use componentDidMount I got same problem
import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './users/login';
import home from './news/index';
class App extends Component {
constructor(props){
super(props);
this.state = {
show: false
}
}
componentWillMount(){
if(sessionStorage.getItem('loginToken')){
this.setState({show: true});
}else{
this.setState({show: false});
}
}
render() {
return (
<div>
{this.state.show?
<div>welcome back</div>:null
}
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/home" component={home} />
</Switch>
</Router>
</div>
)
}
}
export default App;
Thank you so much for helping me.

This issue is componentWillMount only fires once when the app first is run since it is the most top level component in the tree.
You should look to pass a function as a prop into the Login component and call it in the login component to trigger a state change back in the parent component. You could follow an approach to doing so in this article.
The easiest approach would be to just move that welcome back text into a dashboard or home route this way it mounts and unmounts as you are expecting and you can use your current approach in that component.

Related

React JS : this page is slowing down firefox, to speed up the browser , stop this page

so I have a react movie website which fetches data from tmbd , on home page it shows all trending movies data , and on the favorites page it shows all favorite movies , i routed these two pages but when i try to access favorites my browser gets really slow and tells me to stop the webpage , only after reloading the page , i get redirected to favorites page any solution in this ?
this is my nav bar where the links are , when i try to access the favourites page its shows that the page is slowing down
import React, { Component } from 'react'
import { Link } from "react-router-dom";
export default class Navbar extends Component {
render() {
return (
<div style={{display:'flex', padding:'0.5'}}>
<Link to="/" style={{textDecoration:'none'}}>
<h1 style={{marginTop:'1rem',marginLeft:'1rem'}}>Movies App</h1>
</Link>
<Link to='/favourites' style={{textDecoration:'none'}}>
<h2 style={{marginLeft :'5rem',marginTop:'2rem'}}>Favorites</h2>
</Link>
</div>
)
}
}
Here is my APP.js
import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import Navbar from './Components/Navbar';
import Banner from './Components/Banner';
import Movies from './Components/Movies';
import Favourite from './Components/Favourite';
import {Switch,Route, BrowserRouter,Routes} from 'react-router-dom';
function App() {
return (
// <>
// <Navbar></Navbar>
// <Banner></Banner>
// <Movies></Movies>
// </>
<BrowserRouter>
<Navbar/>
<Routes>
<Route exact path="/" element={<HomePage/>}/>
<Route exact path="/favourites" element={<Favourite/>}/>
</Routes>
</BrowserRouter>
);
}
function HomePage() {
return (
<>
<Banner />
<Movies />
</>
);
}
export default App;
when i try to access the individual file without routing it works fine ,but when i try to access this with routing my browser starts to slow down and the data isnt fetched untill i reload the page
my Github repo link: https://github.com/faizxmohammad/React-MovieApp/tree/master/src
I am expecting to fetch data of favorites pages without slowing down the browser
I cloned your code.
The problem is in the file Favorites.js, line 45. You are changing the state, inside the render method. This causes loops. Move any state change, outside render method. Why? This is the workflow:
State change -> renders the component
You are changing your state, inside render component, so it becomes:
state change -> render (state change inside so leads to state change) -> state change -> render render (state change inside so leads to state change) ... infinite loop.

Issue with react-router-dom and github pages

So, first I had an issue with the routes not working, but I resolved that with react-router-dom's "baseline" property, but now despite the home page loading, the subsequent links render beneath the first component, which is supposed to dissapear entirely when the link is clicked.
It works fine locally.
This is my app.js
import React from 'react';
import './App.css';
import Navbar from './Component/Navbar/Navbar';
import RecipeList from './Component/RecipeList/RecipeList';
import { Switch, Route, BrowserRouter } from 'react-router-dom'
import RecipeItemDetails from './Component/RecipeItemDetails/RecipeItemDetails';
function App() {
return (
<BrowserRouter basename={process.env.PUBLIC_URL}>
<div className="App">
<Navbar/>
<Route exact path="/" component={RecipeList} />
<Route path="/recipes/:id" component={RecipeItemDetails} />
</div>
</BrowserRouter>
);
}
export default App;
any ideas? I've tried adding "exact" to the second route which didnt work, and I've also tried wrapping the router in a "switch", but that doesnt work either. I'm stumped.
your routes are inside el. so the the re rendered part when the route change is the Route components , and the div and navbar not re-rendered this is the reason you see the new routes beneath the first component, you should do something like this
<BrowserRouter basename={process.env.PUBLIC_URL}>
<Route exact path="/" component={RecipeList} />
<Route path="/recipes/:id" component={RecipeItemDetails} />
</BrowserRouter>
and then in the RecipeList and RecipeItemDetails import the Navbar and enclose it in the desired

issue with react-router showing component when not in route

I am using react-router and having some difficulties with it's behaviour.
The Nav shows on all pages as desired. However, the Profile shows on all pages too. I only want to show this on /home and also on the /music and /players pages, which it does. However, it also shows on the /charts page which is confusing me.
My code looks like the following.
import React from 'react';
import { Route } from 'react-router-dom'
import Nav from './components/Nav'
import Profile from './components/Profile'
import Players from './components/Players'
import Music from './components/Music'
import Charts from './components/Charts'
const App = () => {
return (
<section>
<Nav />
<Route path="/home">
<div>
<Profile avatarUrl={ avatarUrl }/>
<Route path="/players" component={Players}/>
<Route path="/music" component={Music}/>
</div>
</Route>
<Route path="/charts" component={Charts}/>
</section>
)
}
export default App;
I have read through the docs, tried putting in a Switch component, added exact to the home route but this leads to other unexpected behaviour.
Can anyone advise what I am doing wrong?
Thanks Pete!
Try this:
import React from 'react';
import { Route, BrowserRouter as Router } from 'react-router-dom'
import Nav from './components/Nav'
import Profile from './components/Profile'
import Players from './components/Players'
import Music from './components/Music'
import Charts from './components/Charts'
const Home = ({match}) => {
return (
<div>
<Profile avatarUrl={ avatarUrl }/>
<Route path=`${match.url}/players` component={Players}/>
<Route path=`${match.url}/music` component={Music}/>
</div>
);
};
const App = () => {
return (
<section>
<Nav />
<Router>
<Switch>
<Route path="/charts" exact={true} component={Charts}/>
<Route path="/home" component={Home} />
</Switch>
</Router>
</section>
)
}
export default App;
I haven't tested this, but this should work.
Assuming that you're using react-router v4, I don't know if you can actually use your home route in the way you've used it.
In the code above, Switch basically renders the first match between the routes specified under it. The exact keyword will ensure that only /charts path will display the Charts component.
The Home component will render in any path that starts with /home.
Now, for path /home/players, you'll see the Profile and the Players component, whereas for path /home/music, you'll see the other combination.
Hope this helps. :)
Edit:
Added Router to the code.
Edit:
Working code available here: https://codesandbox.io/s/8x9pql9m19
Change route on right hand side to:
/home
/home/players
/home/music
/charts

React Router V4 is updating URL, but not refreshing (React, Redux)

I am trying to use React-Router V4 to add routes to my app, but it is not working at all. Basically, I'm trying to programatically change the route with history.push, which is updating the browser URL, but not changing anything inside the actual app.
NOTE: I am using redux.
The only answered question on this issue is:
React history.push() is updating url but not navigating to it in browser
However, I've tried the answer to the above question, and it doesn't work for me.
Here are the important snippets:
Topmost file (index.js)
...
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<App/>
</Provider>
</BrowserRouter>
, document.getElementById('root'));
...
Component containing routes
...
export default function ContentRouter() {
return <div className="content">
<Route exact path="/dashboard" component={TmpDashboard}/>
<Route exact path="/" component={() => {
return <h1>Home</h1>
}}/>
</div>
}
Component pushing routes
...
this.handleGroupClick = (group) => {
this.props.history.push(`/groups/${group}`);
this.props.onOpenChange(false);
};
...
export default withRouter(connect(mapStateToProps, mapDispatchToProps(DrawerConnector))
After a lot of searching in the completely wrong place, I figured out what was wrong. The lack of updating was being caused by Redux
Whenever a component is wrapped in connect it causes updates to be blocked, and the view doesn't update.
The solution is mentioned here:
https://github.com/ReactTraining/react-router/issues/4671#issuecomment-285320076
Basically, every component with a Route or a React-Router thing inside it must be wrapped with withRouter
EDIT: Only the top level component that uses connect should be wrapped in withRouter. Note that this may cause performance issues
EDIT: The way I got around the increased coupling was to have a component just to deal with routes. That way, I only need to wrap that component, and the component with a Router.
Here's a setup that works:
The main App:
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
/* this is a common component and happens to need to redirect */
<Route component={CommonComponentThatPushesToHistory} />
<div id="body">
/* I usually place this switch in a separate Routes file */
<Switch>
<Route exact path="FooRoute" component={FooPage}/>
<Route exact path="BarRoute" component={BarPage}/>
</Switch>
</div>
/* another common component which does not push to history */
<Footer />
</div>
</BrowserRouter>
);
}
}
export default withRouter(App);
CommonComponentThatPushesToHistory
class CommonComponentThatPushesToHistory extends React.Component{
render(){
return(
<button type="button"
onClick={() => {this.props.history.push('some-page');}}>
Click to get redirected</button>
);
}
}
FooPage may have a child component that pushes to history:
class FooPage extends React.Component{
render(){
return(
<MyChild history={this.props.history} />
);
}
}
Then MyChild component can push to history the same way CommonComponentThatPushesToHistory does.

React not updating the DOM (Laravel)

I have set up a basic react app with hash navigation. Problem is when I click on any link to navigate between pages, I see that the hash in the url is changing properly, as well as I added a console.log in my layour's render to see if it's getting called and it is, with proper this.props.children values, however the page is not rendering anything. If I go to any route and refresh the page I see the correct components rendered, but if I navigate somewhere from there noting gets rendered until I refresh again.
import React from "react";
import ReactDOM from "react-dom";
import { IndexRoute, Router, Route, Link, hashHistory as history } from 'react-router';
class Layout extends React.Component {
render() {
console.log(this.props, document.location.hash);
return <div>
<div>
<span>LEYAUTI MLEAYTI {Math.random()}</span>
</div>
<div>
{this.props.children}
</div>
<div>
{this.props.params.project}
</div>
</div>
}
}
class CreateProject extends React.Component {
render() {
return <div>
<h1>Create PROEKT</h1>
</div>
}
}
class Projects extends React.Component {
render() {
return <div>
<h1>PROEKTI MROEKTI</h1>
<Link to="/projects/create">New project</Link>
</div>
}
}
ReactDOM.render(
<Router history={history}>
<Route path="/" component={Layout}>
<IndexRoute component={Projects}/>
<Route path="projects/create" component={CreateProject}/>
</Route>
</Router>,
document.getElementById('app-root'));
Here is a visual of what's happening in the console when I navigate on a couple routes, but the DOM remains unchanged
This may be an issue with hashHistory. Which react-router version are you using? With v4 and above, you need to use history like so -
import createHistory from 'history/createHashHistory'
const history = createHistory()
// pass history to the Router....
Your component didn't actually unmount/remount if you only update your hashtag in your url. The route however, is updated. So you can only see the component loads content for once when you refresh the page.
You will need to create state variables and update it in a routeChange handler callback and bind the updated state variable to your view by using setState. Then the component can get updated.
See this post for how to add the route change listener (https://github.com/ReactTraining/react-router/issues/3554)
Alright, so I got down to the bottom of it.
The problem was that I was including my client.min.js file before the default app.js file of laravel 5.4's default layout. For some reason it broke react in a very weird way. What I had to do is switch the order in which the two files were included.

Categories