dispatch inside of child useEffect causes infinite rendering - javascript

App.js
return (
<Router history={createBrowserHistory}>
<Routes>
<Route path="/" element={<LandingPage />} />
<Route
path="/login"
element={
<LoginAuth redirectTo="/dashboard">
<SignIn set_token={setAuthToken} setUserType={setUserType} />
</LoginAuth>
}
/>
<Route path="/register" element={<SignUp />} />
<Route
path="/dashboard/*"
element={
<RequireAuth redirectTo="/login">
<UserDashboard />
</RequireAuth>
}
/>
<Route path="/register/subscription" element={<Package />} />
<Route path="/contact" element={<Contact />} />
<Route path="/pricing" element={<Pricing />} />
<Route path="/features" element={<Features />} />
</Routes>
</Router>
);
UserDashboard.js
when route is 'localhost../dashboard' it renders this component and in this useeffect I append URL with home so that home component render automatically.
useEffect(() => {
history("home");
}, []);
return (
<div className="dash-cont background-blue">
<header className="head-cont">
<div className="top-left-head">
<div className="left-header">
<a href="/" className="b-brand">
<span className="logo">SchoolSavvy</span>
</a>
<a href="#!" className="mob-toggler" onClick={onToggle}>
<Hamburger
className="hamburger-react"
toggled={isOpen}
toggle={setOpen}
/>
</a>
<div className="right_head_popup">
<MoreVertIcon />
</div>
</div>
<div className="right-header">
<NotificationsNoneOutlinedIcon className="notify-ico" />
<PersonOutlineOutlinedIcon className="person-ico" />
</div>
</div>
</header>
<div className="body-div">
<UserSidebar is_Open={isOpen} on_Toggle={onToggle} />
<div className="dash-info">
{/* Heading */}
<PathHeading />
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/school/*" element={<SchoolComp />} />
<Route path="/student/*" element={<></>} />
<Route path="/parent/*" element={<></>} />
<Route path="/teacher/*" element={<></>} />
<Route path="/class/*" element={<></>} />
<Route path="/exam/*" element={<></>} />
<Route path="/attendance/*" element={<></>} />
<Route path="/timetable/*" element={<></>} />
</Routes>
</div>
</div>
</div>
);
Home.js
when this component is rendered, dispatch in useEffect causes infinite rendering, anyone knows what's the problem? Thanks
const Home = () => {
const dispatch = useDispatch();
useEffect(() => {
console.log("home rend");
dispatch(loadDashboard());
}, []);
return (
<>
{/* Cards */}
<Card />
<div className="sch_summary">
{/* Charts */}
<BarChart />
<NoticeBoard />
</div>
<Calendar />
</>
);
};
Here is loadDashboard action which is dispatched by useEffect
export const loadDashboard = () => async (dispatch, getstate) => {
try {
dispatch({
type: actionType.DASHBOARD_REQ,
});
console.log(`tokennn: ${getstate().user.token}`);
const { data } = await axios.get("/v1/user/dashboard/detail", {
headers: {
Authorization: `Bearer ${getstate().user.token}`,
},
});
dispatch({
type: actionType.DASHBOARD_SUCCESS,
payload: data.user,
});
} catch (error) {
console.log(`falii: ${error}`);
dispatch({
type: actionType.DASHBOARD_FAILURE,
payload: error.response.data,
});
}
};

One solution is to add the dispatch actions that cause infinite rerender to ref using useRef.
import { useRef } from 'react';
function useAddFnToRef(fn) {
const refProps = useRef({ fn });
return refProps.current.fn;
}
const Home = () => {
const dispatch = useDispatch();
const onLoadDashboard = useAddFnToRef(()=>dispatch(loadDashboard()))
useEffect(() => {
console.log("home rend");
onLoadDashboard();
}, [onLoadDashboard]);
return (
<>
{/* Cards */}
<Card />
<div className="sch_summary">
{/* Charts */}
<BarChart />
<NoticeBoard />
</div>
<Calendar />
</>
);
};

Related

Como llevar el valor de un estado de un componente a otro?

I have this navbar component and it contains a "darkmode" icon, which executes a "useState function to change the icon from light to dark, adding an "active" class, and I would like to carry that same "darkModeToggle" value to the initial component in "App" to add a "dark" to the layout class.
export default function Navbar() {
const [darkModeToggle, setDarkModeToggle] = useState(false);
return (
<>
<header className='header'>
<div className='header__container'>
<div
className={
darkModeToggle
? 'header__container__darkmode active'
: 'header__container__darkmode'
}
onClick={() => {
setDarkModeToggle(!darkModeToggle);
}}
>
<BiSun className='sun' />
<BiMoon className='moon' />
</div>
</div>
</header>
</>
);
}
export default function App() {
return (
<div className='layout'>
<Navbar />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/services' element={<Services />} />
<Route path='/contact' element={<Contact />} />
<Route path='*' element={<NotFound />} />
</Routes>
</div>
);
}
Put the state in the parent component in this case App and pass the prop throught Navbar
export default function App() {
const [darkModeToggle, setDarkModeToggle] = useState(false);
return (
<div className='layout'>
<Navbar darkModeToggle={darkModeToggle} setDarkModeToggle={setDarkModeToggle}/>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/services' element={<Services />} />
<Route path='/contact' element={<Contact />} />
<Route path='*' element={<NotFound />} />
</Routes>
</div>
);
}
and in the Navbar
function Navbar({darkModeToggle, setDarkModeToggle}) {
return (
<>
<header className="header">
<div className="header__container">
<div
className={
darkModeToggle
? "header__container__darkmode active"
: "header__container__darkmode"
}
onClick={() => {
setDarkModeToggle(!darkModeToggle);
}}
>
<BiSun className="sun" />
<BiMoon className="moon" />
</div>
</div>
</header>
</>
);
}

No routes matching location "/dash/1"

I have the following problem. my route is not registered and i dont know why.
Links
dashboard.jsx
this code generates all the links.
<div className="flex w-3/4 m-auto flex-col mt-10 xl:w-1/2">
{questions.map(({ id, question }) => {
return (
<Link to={`/dash/${id}`}>
<QuestionHeader question={question} />
</Link>
);
})}
</div>
/dash/1,/dash/2,.... are generated by the map function above.
i have two files that represent the routes.
NavRoutes
const NavRoutes = () => {
return (
<Routes>
<Route path="/:id" element={<Question />} />
<Route path="" element={<Dashboard />} />
</Routes>
);
};
export default NavRoutes;
here is the Main component
const Main = () => {
return (
<div>
<NavBar />
<NavRoutes />
<Footer />
</div>
);
};
export default Main;
and the main routes for authentication and accessing the main page
const App = () => {
let { user } = useAuthContext();
return (
<div className="w-full bg-slate-700 block fixed h-full">
<Header />
<Router>
<Routes>
<Route
path="/dash"
element={!user ? <Navigate to="/auth" /> : <Main />}
>
</Route>
<Route path="" element={<Login />} />
</Routes>
</Router>
</div>
);
};
when i try to access /dash/1, i get the following error
router.ts:11 No routes matched location "/dash/1"
Did you try the following in your NavRoutes (prepending '/dash' to '/:id'):
<Route path="/dash/:id" element={<Question />} />
i solved this by doing the following
const App = () => {
let { user } = useAuthContext();
return (
<div className="w-full bg-slate-700 block fixed h-full">
<Header />
<Router>
<Routes>
<Route
path="/dash/*"
element={!user ? <Navigate to="/auth" /> : <Main />}
>
</Route>
<Route path="/auth" element={<Login />} />
</Routes>
</Router>
</div>
);
};
you need to include a * when nesting deeper

how to render same component in every route

import ...
const App = () => {
const [showModal, setShowModal] = useState(false);
const toggleModalShow = () => {
setShowModal(!showModal);
};
return (
<div className="app">
<Router>
<ScrollToTop>
<Routes>
<Route
exact
path="/"
element={
<>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<main className="main">
<Home />
</main>
</>
}
/>
<Route
path="/games/:game"
element={
<>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<GameLobby />
</>
}
/>
<Route
path="/games"
element={<PrivateRoute isLoggedIn={isLoggedIn} />}
>
<Route
path="/games"
element={
<>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<Games />
</>
}
/>
</Route>
</Routes>
</ScrollToTop>
</Router>
</div>
);
};
export default App;
Hi all.i want to show <Header /> component in every route but to this i have to use <Header /> component in every <Route />. Is there any way to do that without ? Finally i would be appreciate if you give me feedback about project.
repo : https://github.com/UmutPalabiyik/mook
deploy: https://mook-f2b4e.web.app
for testing:
username: test
pass: 123
Just move the Header above Routes:
return (
<div className="app">
<Router>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<ScrollToTop>
<Routes>
<Route
exact
path="/"
element={
<>
<main className="main">
<Home />
</main>
</>
}
/>
...
</Routes>
</ScrollToTop>
</Router>
</div>
);
};

Nested routes in react-router-dom

enter image description here
How to navigate through the tabs in react.
Since I am currently in a tab, I have already used react route and the nested route does not work. how to make a transition through the masonry. Through a nested route or otherwise?
I have a react application inside this I have component with my routers
export const Container = (props) => {
return (
<Switch>
<Route exact path="/">
<Redirect to={PERSONAL} />
</Route>
<Route path={PAGE} render={() => <PicturesMainPage />} />
<Route path={PERSONAL} render={() => <PersonalPage />} />
<Route path={PERSONAL_SETTINGS} render={() => <PersonalSettingsPage />} />
</Switch>
);
};
In this component I have inside this component I drow an information about user with menu and i wand to drow athother components for click in to menu
export const PersonalPage = () => {
return (
<div className="container">
<PersonalInfo />
<div className="personal-area__galery">
<Switch>
<Route exact path={PERSONAL}>
<Redirect to={PERSONAL_GALLERY} />
</Route>
<Route path={PERSONAL_GALLERY} render={() => <Gallery images={images} />} />
<Route path={PERSONAL_COLLECTIONS} render={() => <Collections />} />
<Route path={PERSONAL_STATISTICS} render={() => <Statistics />} />
</Switch>
</div>
</div>
);
};
Person info
let menu = [
{ href: PERSONAL_GALLERY, text: 'Галерея' },
{ href: PERSONAL_COLLECTIONS, text: 'Коллекции' },
{ href: '/personal/statistics', text: 'Статистика' },
];
let person = {
profileName: 'Top Waifu',
profileTag: '#topwaifu',
profileDescription: 'Самая топовая вайфу твоего района',
subscribers: '5.1m',
subscriptions: 246,
};
export const PersonalInfo = (props) => {
return (
<div>
<div className="personal-area__profile">
<div className="personal-area__profile__description">
<PersonalAvatar img={'assets/img/testImg4.png'} />
<PersonalDescription
profileName={person.profileName}
profileTag={person.profileTag}
profileDescription={person.profileDescription}
subscribers={person.subscribers}
subscriptions={person.subscriptions}
/>
<div className="personal-area__profile__description__icons">
<Share />
<Settings />
<MoreOptions />
</div>
</div>
</div>
<div className="personal-area__menu">
<ul>
{menu.map((elem, i) => (
<MenuElement key={i} menulink={elem.href} menuName={elem.text} />
))}
</ul>
</div>
</div>
);
};
take a look at this codesandbox I made.
https://codesandbox.io/s/frosty-cdn-1fn0u?file=/src/App.js
Here you can see a clear example of nesting routes.

How to hide nav if user is not logged in react

Route.js
const Layout = () => {
const SecuredRoute = ({ ...props }) => (
console.log(props.path),
<Route path={props.path} render={(data) => (
console.log(data),
localStorage.getItem('accessToken')
? <props.render {...data} />
: <Redirect to='/login' />
)} />
)
return (
<>
<BrowserRouter>
<Navbar /> // It needs to be hidden if user is not logged in
<div className='layout'>
<Switch>
<Route exact path='/home' component={Home} />
<Route exact path='/login' component={Login} />
<SecuredRoute exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route exact path='/add' component={AddBlog} />
<Route exact path='/edit/:id' component={UpdateBlog} />
<Route exact path='/blog/:id' component={Blogdetail} />
<Route component={Home} />
</Switch>
</div>
<Footer />
</BrowserRouter>
</>
)
}
export default Layout
I want if the user is not logged in then navbar must be hidden. It means when route = '/login' navbar needs to be hidden. u have tried out many things but nothing works. I am new to React. Any help will be appreciated?
You can create a boolean variable and short-circuit it.
render() {
const visible = true;
const notVisible = false;
return (
<div>
{visible && <p>I am visible</p>}
{notVisible && <p>I am not visible</p>}
</div>
);
}
Try this in the Navbar component my friend:
const [loggedIn, setLoggedIn] = useState(false);
const Layout = () => {
const SecuredRoute = ({ ...props }) => (
console.log(props.path),
<Route path={props.path} render={(data) => (
console.log(data),
localStorage.getItem('accessToken')
? <props.render {...data} />
: <Redirect to='/login' />
)} />
)
return (
<>
<BrowserRouter>
<Navbar loggedIn={loggedIn} /> // It needs to be hidden if user is not logged in
<div className='layout'>
<Switch>
<Route exact path='/home' component={Home} />
<Route exact path='/login' component={() => <Login setLoggedIn={setLoggedIn} />} />
<SecuredRoute exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route exact path='/add' component={AddBlog} />
<Route exact path='/edit/:id' component={UpdateBlog} />
<Route exact path='/blog/:id' component={Blogdetail} />
<Route component={Home} />
</Switch>
</div>
<Footer />
</BrowserRouter>
</>
)
}
export default Layout
I gave a setState to login component. You give a true boolean when the user logs in, loggedIn(true) and the parent state changes.
And in the Navbar component:
return(
loggedIn
?
//The Body of NavBar
:
""
}
)

Categories

Resources