error with nested route ( react-router ) - javascript

I have an issue with setState().
Here is my routes.tsx file
export const Routes = (props:any) => (
<Router {...props}>
<Route path="/" component={Miramir}>
<Route path="/profile">
<IndexRoute component={Profile} />
<Route path="/profile/update" component={ProfileUpdate} />
</Route>
</Route>
So, when i trying to use /profile/update route
I have an warning and see that component which only for /profile route exists on /profile/update
This is an error
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the CountDown component.
Component CountDown
componentDidMount = () => {
let timeLeft = this.secondsToTime(this.state.date);
this.setState({time: timeLeft});
}
_countDown = () => {
this.setState({
time: this.secondsToTime(this.state.date)
})
}
Calling _countDown every sec
Hope your help!
Thanks

You probably call _countDown() via setInterval() I'd imagine. Did you clear that Interval in componentWillUnmount()?

you can not call the _countDown before the component mount (it means the component render method is already called and then you calling _countDown function).
calling _countDown inside setInterval may solve, but may fail again if you render method take more time than time provided in setInterval.
_countDown = () => {
this.setState({
time: this.secondsToTime(this.state.date)
})
}

Related

How to navigate programmatically react-router-dom v6

I came back to react world after a few years. And things certainly have changed for good. I'm using MemoryRouter for my app. And I can navigate fine by using Link. But useNaviate hook is not working as expected. It does nothing on the page. Could you please help me here? Here is my code:
Router:
<MemoryRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</MemoryRouter>
Here is how I'm trying the navigation:
function Home() {
// demo purpose
const navigate = useNavigate()
navigate('/dashboard')
}
I'm not sure if I'm using it right, or if I need to do something else here.
The code is calling navigate as an unintentional side-effect directly in the function component body.
Either call navigate from a component lifecycle or callback to issue an imperative navigation action:
function Home() {
const navigate = useNavigate()
useEffect(() => {
if (/* some condition */) {
navigate('/dashboard');
}
}, [/* dependencies? /*]);
...
}
Or conditionally render the Navigate component to a declarative navigation action:
function Home() {
...
if (/* some condition */) {
return <Navigate to="/dashboard" />;
};
...
}
The problem was that I was calling navigate directly when the component was rendering. It should either be called in an event, or it should be called in useEffect hook.
Make your navigate in function call or in useEffect like this:
function Home() {
// demo purpose
const navigate = useNavigate()
useEffect(() => {
navigate('/dashboard')
}, []);
}

React: How to update parent component's useEffect hook when using routes

I use the useEffect hook to dispatch the getQuestions function in order to get the data from the server
function App () {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getQuestions());
}, [dispatch]);
return (
<Routes>
<Route exact path="/" element={<Layout/>}>
<Route path="repetition" element={<Repetition/>}/>
<Route path="family" element={<Family/>}/>
</Route>
</Routes>
);
}
The problem is that when I, for example, open the family link (which I declared in the App function), initially I get the data, but when I refresh the page, the data disappears.
I certainly understand that when the page is refreshed the parent App component is not rendered from this and I get an error, similar issues I have looked at in the forums where it was suggested to use withRouter which updates the parent component, but my version of react-router-dom does not supports withRouter, except that I don't want to downgrade my version of react-router-dom to use withRouter.
I would like to know if there is any way to fix this problem.
I tried the option that #Fallen suggested, i.e. I applied the useEffect hook in each child element and analyzed this approach in GoogleLighthouse, and I'm happy with the results.
Here is my final code in child component
function Family () {
const dispatch = useDispatch();
const questions = useSelector(state => state.QuestionsSlices.familyQuestions);
useEffect(() => {
dispatch(getFamilyQuestions());
}, [dispatch]);
return (
<>
{questions.data.map((item, idx) => (
<div key={idx}>
{ idx + 1 === questions.score && CheckQuestionsType(item, questions) }
</div>
))}
</>
);
}

Fetch data before resolve route

I´m using for routing "react-router" lib. Before render page component, I need fetch data. I want show loader before every routing, because all routes need data from server. All my components is driven by controller, so my solution for this is create this controller in constructor of all components, and on create controller fetch data.
It works, but I´m using typescript and I want access to data without (!) check for data. Better solution for that use wrapper component which wait for data and render currently page. For first routing it works, but componentDidMounnt "below in code" is called only once, so second rounting doesnt work.
<Router>
<Switch>
<MyRoute path="/login" component={LoginPage} exact={true} />
<MyRoute path="/reg" component={RegistrationPage} exact={true} />
</Switch>
</Router>
/*MyRoute*/
async componentDidMount() {
try {
await this.props.routeController.getController(this.props.path).then((controller: PageController) => {
this.setState({
controller: controller
})
this.props.routeController.loading = false;
})
} catch(err) {
// error handling
}
}
render() {
if (!this.props.routeController.loading) {
const { controller } = this.state;
return (
<this.props.component controller={controller} />
)
}
return <div>LOADING</div>;
}
So I need fetch data before routing. After that I need render page component with data in props. Is it possible or Is it good solution for this problem? If not, how can I solve problem with asynchronous routing. Thank you :-)
Make state isLoading : false,
Then in componentWiilMount() / DidMount() set isLoading state true.
After on fetch sucess reset isLoading to false;
componenetWillMount/didMount(){
this.setState({
isLoading: true
})
fetchData().then(res => this.setState(isLoading: false))
.catch(err => this.setState({isLoading: false}));
render(){
return(
{this.state.isLoading ? <Loader /> : <Component View /> }
)
}
You also could use react-router-loading to fetch data before switching the page.
You only need to mark routes with the loading prop and tell the router when to switch the pages using the context in components:
import { Routes, Route } from "react-router-loading";
<Routes> // or <Switch> for React Router 5
<Route path="/page1" element={<Page1 />} loading />
<Route path="/page2" element={<Page2 />} loading />
...
</Routes>
// Page1.jsx
import { useLoadingContext } from "react-router-loading";
const loadingContext = useLoadingContext();
const loading = async () => {
// loading some data
// call method to indicate that loading is done and we are ready to switch
loadingContext.done();
};

How to handle async request in React-router wrapper

I want to check if user is authenticated in my React application. Using this guide.
I wrote a wrapper over my <Route /> class that check, if user is authenticated, then we render component, if not, we just redirect him to sign-in page.
const IsAuthenticatedRoute = function ({ component: Component, ...rest }) {
return (
<Route {...rest} render={async (props) => {
return (
await store.isAuthenticatedAsync() === true // here is the point of troubles
? <Component {...props} />
: <Redirect to={{
pathname: '/sign-in',
state: { from: props.location }
}} />
)
}} />)
}
And I use it in my router like this:
ReactDOM.render(
<Provider store={appStore}>
<Router>
<div>
<Switch>
<Route exact path='/' component={App} />
<IsAuthenticatedRoute path='/protected-route' component={Profile} />
</Switch>
</div>
</Router>
</Provider>
,
document.getElementById('root')
)
I want to execute my async request to the server to check if user is authenticated. I've tried to add async keyword to my functions over await call, but it produces an error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.. I almost tried to use promises, but it isn't help too. When I use Promise inside my function and return <Route /> in .then() operator, React says me: IsAuthenticatedRoute(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
So I expect to handle my async function, and then after I get response from server, give access to my user to visit this page. Is it possible only with sending synchronous request to my server or there're another ways to keep my code async and pass user to the protected page?
An async function cannot be rendered as a component, because you'd be rendering a Promise, not a pure function. Pure functions can be rendered, if they return an instance of a component. Promises must be resolved before they can be rendered.
The solution is to start the asynchronous call when the component is mounted and make the component stateful, so that it can mutate when the call is resolved. You will need to render something while waiting for a response. You can render null, but a loading spinner would be more appropriate. This way we have something to render at all times and won't run into errors trying to render a component that isn't defined yet.
Here's my quick hack at what the component could look like:
class RouteRender extends React.Component {
constructor(props) {
super(props)
this.state = { authorized: null }
}
componentDidMount() {
// setState is called once the asynchronous call is resolved.
store.isAuthenticatedAsync().then(
authorized => this.setState({ authorized})
)
}
render() {
if(this.state.authorized === true) {
const { component: Component, componentProps } = this.props
return <Component {...componentProps} />
} else if(this.state.authorized === false) {
return (<Redirect to={{
pathname: '/sign-in',
state: { from: props.location }
}} />)
}
return <LoadingSpinner />
}
}
const IsAuthenticatedRoute = function ({ component: Component, ...rest }) {
return (
// render is now a function rather than a Promise.
<Route {...rest} render={props => <RouterRender componentProps={props} component={Component} />} />
)
}

React-router doesn't remount component on different paths

I have a component in my react app which is a form. The form is used to create new licenses OR edit existing licenses. Either way it is only one component and it checks on componentDidMount() which "pageType" (add/update) it is.
Now to my problem, when I'm using the form to edit a license (licensee/:id/edit) and I’m clicking the button which is bidet to create a new license (licensee/add), it will not remount the component.
It will change the URL but all the preloaded data is still in the form.
LicenseeForm = Loadable({
loader: () => import('./license/LicenseeForm'),
loading: 'Loading..'
});
render() {
return (
<Router>
<Switch>
<LoginRoute exact path="/" component={this.LoginView}/>
<LoginRoute exact path="/login" component={this.LoginView}/>
<PrivateRoute exact path="/licensees/add" component={this.LicenseeForm}/>
<PrivateRoute exact path="/licensees/:id/update" component={this.LicenseeForm}/>
<Route path="*" component={this.NotFoundPage}/>
</Switch>
</Router>
)
}
const PrivateRoute = ({component: Component, ...rest}) => (
<Route
{...rest}
render={props =>
authService.checkIfAuthenticated() ? (<Component {...props} />) :
(<Redirect
to={{
pathname: "/login",
state: {from: props.location}
}}/>
)
}
/>
);
Component:
componentDidMount() {
const locationParts = this.props.location.pathname.split('/');
if (locationParts[locationParts.length-1] === 'add') {
this.setState({pageType: 'add'});
} else if (locationParts[locationParts.length-1] === 'update') {
this.setState({pageType: 'update'});
...
}}
EDIT
This is how it works now:
<PrivateRoute exact path="/licensees/add" key="add" component={this.LicenseeForm}/>
<PrivateRoute exact path="/licensees/:Id/update" key="update" component={this.LicenseeForm}/>
If you do need a component remount when route changes, you can pass a unique key to your component's key attribute (the key is associated with your path/route). So every time the route changes, the key will also change which triggers React component to unmount/remount.
When the route is same and only path variable changes which in your case is "id", then the component at the top level of your route receives the change in componentWillReceiveProps.
componentWillReceiveProps(nextProps) {
// In this case cdm is not called and only cwrp know
// that id has been changed so we have to updated our page as well
const newLicenseId = nextProps.match.params.id;
// Check id changed or not
if(currentLicenseId != newLicenseId) {
updateState(); // update state or reset state to initial state
}
}
I am pasting code which enables you to detect that page is changed and update the state or re-assign it to initial state. Also, suppose you come on license page first time then save current Id in a variable. That only you will use in componentWillReceiveProps to detect change.
Use props 'render' instead component.
As per Doc Component props remount while parent state changes but render props update.
https://reacttraining.com/react-router/web/api/Route/route-render-methods

Categories