Show progress bar BEFORE go to route - javascript

I'm developing a universal react application using redux. I use react-router v3.
I want to show a progress bar "BEFORE" going to next route (next route is fetching data from API).
for example imagine I am in "Home Page" and I want go to "Submit Page". when I click on the Submit Link (react-router Link) first show a progress bar in "Home Page" and wait for Submit page data fetching and then go to "Submit Page".
My React Routes:
<Route component={App}>
<Route path={HomingRoutes.HomePage} component={HomePage}/>
<Route path={HomingRoutes.SubmitPage} component={SubmitPage}/>
<Route path={HomingRoutes.SearchPage} component={SearchPage}/>
<Route path={`${HomingRoutes.DealsPage}`} component={DealsPage}/>
<Route path={`${HomingRoutes.DealPage}/:id(/:title)`} component={DealPage}/>
<Route path={`${HomingRoutes.Detail}/:id(/:title)`} component={DetailPage}/>
<Route path="*" component={NoMatch}/>
</Route>
in Home Page :
<Link to "/Submit" >Submit</Link>
My Submit page Container code is :
class SubmitContainer extends React.Component {
static readyOnActions(dispatch) {
return Promise.all([
dispatch(SubmitActions.fetchSubmitInitialData()),
]);
}
componentDidMount() {
this.props.fetchSubmitInitialData();
}
}
"fetchSubmitInitialData" is an action creator that fetch data from API.

One solution would be to pass a placeholder component as props to your SubmitPage that will render only when data is fetching.
So you can use something like:
class SubmitContainer extends React.Component {
state = {
loading: true
progress: 0,
}
componentDidMount() {
// fetch some data and update the state
// consider updating the progress more often
this.props.fetchSubmitInitialData()
.then(() => {
this.setState({ loading: false, progress: 100 })
})
}
render() {
const Placeholder = this.props.placeholder
// Show the placeholder when loading
if (this.state.loading) {
return <Placeholder loading progress={this.state.progress} />
}
// Otherwise render your component with the data
return <SubmitPage data={/*..*/}>
}
}
And finally pass you could use the component HomePage as placeholder like this:
<Route path={HomingRoutes.HomePage} component={HomePage}/>
<Route path={HomingRoutes.SubmitPage} render={(props) => (
<SubmitContainer {...props} placeholder={HomePage} />
)}/>
Here I use the render props with React router v4. But I'm sure there is an equivalent for the version 3
Now HomePage will render during data fetching and can use the props loading and progress to show a spinner or something

You can add onEnter hook into your router and add onEnter.js inside your SubmitContainer folder and move fetchSubmitInitialData to the onEnter.js then import your store here and dispatch it. the implementation might looks like this:
Your React-Route
import { onEnterSubmitPage } from './your onEnter path/onEnter'
<Route component={App}>
<Route path={HomingRoutes.HomePage} component={HomePage}/>
<Route path={HomingRoutes.SubmitPage} component={SubmitPage} onEnter={onEnterSubmitPage}/>
<Route path={HomingRoutes.SearchPage} component={SearchPage}/>
<Route path={`${HomingRoutes.DealsPage}`} component={DealsPage}/>
<Route path={`${HomingRoutes.DealPage}/:id(/:title)`} component={DealPage}/>
<Route path={`${HomingRoutes.Detail}/:id(/:title)`} component={DetailPage}/>
<Route path="*" component={NoMatch}/>
</Route>
create onEnter.js file in SubmitPage container:
/**
* Import dependencies and action creators
*/
import { store } from '../../index'
import { fetchSubmitInitialData } from './actions'
/**
* Define onEnter function
*/
export function onEnterSubmitPage() {
store.dispatch(fetchSubmitInitialData())
}
then we can integrate state for progress bar into redux too.
actions.js
/** Import all dependencies here **/
import axios from 'axios'
import { FETCH_SUBMIT_INITIAL_DATA, IS_FETCHING_INITIAL_DATA } from './constants'
export function fetchSubmitInitialData() {
/** this dispatch is from middleware **/
return (dispatch) => {
/** this will set progress bar to true **/
dispatch(fetchSubmitInitialData(true))
/** Your fetching action here, this will depend on your configuration **/
axios.get(`url`, {{ headers: `bearer //your token`}})
.then( (response) => {
dispatch(fetchSubmitInitialData(false))
})
}
}
export function isFetchInitialData(status) {
return {
type: IS_FETCHING_INITIAL_DATA,
status
}
}
so there is no need to fetch the data inside SubmitPage container.
One solution would be to pass a placeholder component as props to your SubmitPage that will render only when data is fetching.
So you can use something like:
class SubmitContainer extends React.Component {
render() {
/** this come from your reducer **/
const { isFetching, submitInitialData } = this.props
// Show the placeholder when loading
if (isFetching) {
return <Loader />
}
// Otherwise render your component
return <SubmitPage data={/*..*/}>
}
}
// Map state to props
const mapStatetoProps = ({ app }) => {
isFetching: //,
submitInitialData: //
}
export default connect(mapStatetoProps, null)(SubmitContainer)

Related

how to detect previous url path react

I am using React, and I am trying to detect the previous path / url that the user is coming from within my app. so if they are coming from /register and land on /index, then how do I log, on /index, that the user came from /register. Is this possible?
you can save previous path in a componentWillReceiveProps lifecycle method.
<Route component={App}>
{/* ... other routes */}
</Route>
const App = React.createClass({
getInitialState() {
return { prevPath: '' }
},
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
this.setState({ prevPath: this.props.location })
}
}
})

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 call React's render method() from another component?

A client request a feature to implement dashboard switching. I'm working on it:
Dashboard.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
// components
import UserDashboard from '../components/dashboard/user-dashboard/UserDashboard.js';
import NewUserDashboard from '../components/new-dashboard/user-dashboard/NewUserDashboard.js';
#connect((state) => {
return {
identity: state.identity.toJS().profile
};
})
export default class Dashboard extends Component {
render() {
const msisdn = this.props.location.state ? this.props.location.state.msisdn : null;
return (
<UserDashboard msisdn={ msisdn }/>
);
}
}
Dashboard.js is the dashboard controller. I have 2 dashboards: UserDashboard, and NewDashboard.
Let's say an user is viewing another screen, and in that screen there's a button. If that button is clicked, the Dashboard will call it's render method, returning NewDashboard instead. And NewDashboard will be automatically displayed. Is this possible?
Calling render method programmatically not possible.
You have to do state update of that particular component if you want to call render method of that component.
Say,if you want to call render method of Dashboard Component,you must call setState on this component. You can do some dummy state lifting for that.
Imagine you have this dashboard:
function DashBoard({index}) {
return index == 0 ? <UserDashBoard /> : <SecondDashBoard />;
}
Without a router:
class ParentComponent extends ReactComponent {
state = {
dashboardIndex: 0
}
changeDashboard() {
this.setState({
dashBoardIndex: (state.dashboardIndex + 1) % 2
})
}
render() {
return (
<div>
<button onclick={() => this.changeDashboard()}>Change dashboard</button>
<Dashboard index={this.state.dashboardIndex} />
</div>
)
}
}
With a router:
<Switch>
<Route match="/component1" component={UserDashboard} />
<Route match="/component2" component={SecondDashboard} />
</Switch>
Also you can use redux.
You can use conditional rendering using state.
You can keep track of currently active tab and use that state to render the desired component.
More often than not, in order to change page views, you would make use of Router. You can configure Routes corresponding to Dashboard
import UserDashboard from '../components/dashboard/user-dashboard/UserDashboard.js';
import NewUserDashboard from '../components/new-dashboard/user-dashboard/NewUserDashboard.js';
#connect((state) => {
return {
identity: state.identity.toJS().profile
};
})
export default class Dashboard extends Component {
render() {
const msisdn = this.props.location.state ? this.props.location.state.msisdn : null;
return (
<BrowserRouter>
<Route path="/dashboard/user" render={(props) => <UserDashboard msisdn={ msisdn } {...props}/>} />
<Route path="/dashboard/new" render={(props) => <NewUserDashboard msisdn={ msisdn } {...props}/>} />
</BrowserRouter>
);
}
}
and on button click you can use a link.
Or else you can conditionally render component based on state change
// components
import UserDashboard from '../components/dashboard/user-dashboard/UserDashboard.js';
import NewUserDashboard from '../components/new-dashboard/user-dashboard/NewUserDashboard.js';
#connect((state) => {
return {
identity: state.identity.toJS().profile
};
})
export default class Dashboard extends Component {
state = {
userDashboard: true
}
onToggle=(state)=> {
this.setState(prevState => ({
userDashboard: !prevState.userDashboard
}))
}
render() {
const msisdn = this.props.location.state ? this.props.location.state.msisdn : null;
return <div>{userDashboard? <UserDashboard msisdn={ msisdn }/>
: <NewUserDashboard msisdn={ msisdn }/>}
<button onClick={this.onToggle}>Toggle</button>
</div>
);
}
}
Probably something like:
class NewDashboard extends React.Component {
static triggerRender() {
this.forceUpdate();
}
// or
static altTriggerRender() {
this.setState({ state: this.state });
}
render() {...}
}
Force React Component Render
Though, it's better to show/hide other components by conditional rendering.
Update:
"This" is not accessible inside a static method. Ignore the code.

React Router v4: Sending requests when navigation changes

I'm coding an authentication with react-router v4 and I'm using the PrivateRoute with render props, like the documentation: Redirects (Auth)
What I'm trying to do is: Whenever the user navigates to a route, I want to dispatch an action to make a request to the backend to verify if he's logged in.
Like this:
// App.js
class App extends Component {
checkAuth = () => {
const { dispatch, } = this.props;
// callback to dispatch
}
render() {
const props = this.props;
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/" component={Login} />
<PrivateRoute
exact
path="/dashboard"
component={Dashboard}
checkIsLoggedIn={this.checkAuth}
/>
{/* ... other private routes here */}
</Switch>
</div>
</Router>
);
}
In PrivateRoute.js I'm listening the route to check if it changes, but when a route changes, this function is called too many times, and that's a problem to dispatch an action to make a request.
// PrivateRoute.js
const PrivateRoute = ({ component: Component, auth, checkIsLoggedIn, ...rest }) => (
<Route
{...rest}
render={props => {
props.history.listen((location, action) => {
if (checkIsLoggedIn) {
// Here I check if the route changed, but it render too many times to make a request
checkIsLoggedIn(); // here is the callback props
}
});
if (auth.login.isLoggedIn) {
return <Component {...props} />;
} else {
return <Redirect to={{ pathname: "/login", state: { from: props.location } }} />
}
}
}
/>
);
I need a help to figure it out a good way to call the backend whenever the route changes.
Creating a Higher Order Component (HOC) is a very clean way to do this. This way, you won't need to create a separate PrivateRoute component, and it would take only one line of change to convert any Component from public to protected, or vice versa.
Something like this should work:
import React from 'react';
import { Redirect } from "react-router-dom";
export function withAuth(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
isUserLoggedIn: false,
isLoading: true
};
}
componentDidMount() {
// Check for authentication when the component is mounted
this.checkAuthentication();
}
checkAuthentication() {
// Put some logic here to check authentication
// You can make a server call if you wish,
// but it will be faster if you read the logged-in state
// from cookies or something.
// Making a server call before every protected component,
// will be very expensive, and will be a poor user experience.
this.setState({
isUserLoggedIn: true, // Set to true or false depending upon the result of your auth check logic
isLoading: false
});
}
render() {
// Optionally, you can add logic here to show a common loading animation,
// or anything really, while the component checks for auth status.
// You can also return null, if you don't want any special handling here.
if (this.state.isLoading) return (<LoadingAnimation />);
// This part will load your component if user is logged in,
// else it will redirect to the login route
if (this.state.isUserLoggedIn) {
return <WrappedComponent authData={this.state} {...this.props} />;
} else {
return <Redirect to={{ pathname: "/login", state: { from: props.location } }} />;
}
}
}
}
Once you have that component in place, all you need to do is use the HOC in any component that you wish to have protected. For example, in your case, the export line in your Dashboard file would be something like this:
/* Dashboard.js */
class Dashboard extends React.Component { ... }
export default withAuth(Dashboard);
and in your App, you can use a simple Route component:
<Route exact path='/dashboard' component={Dashboard} />
Your App does not need to care about which routes are protected, and which ones aren't. In fact, only the actual components need to know that they are protected.
Hope this helps. Cheers! :)

redux-simple-router - perform action based on URL

I'm using Redux with redux-simple-router.
Here's what I'm trying to do. A user hits a URL like so:
http://localhost:3000/#/profile/kSzHKGX
Where kSzHKGX is the ID of the profile. This should route to Profile container filled out with the details of the profile with id kSzHKGX.
My routes look like this:
export default (
<Route path="/" component={App}>
...
<Route path="profile" component={Profile} />
...
</Route>
)
So hitting the above link would give me Warning: [react-router] Location "undefined" did not match any routes
My container looks like this:
#connect(
state => state.profile,
dispatch => bindActionCreators(actionCreators, dispatch)
)
export class Profile extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const { getProfileIfNeeded, dispatch } = this.props
getProfileIfNeeded()
}
render() {
return (
<section>
...
</section>
)
}
}
So normally my container would just be populated from the state as usual in Redux.
Basically I need to have a way of doing some wildcard in the route. Than I need to pass the URL to the action that would pull up the right profile from an API. The question is, is it doable with react-simple-router? Can I do that somehow using UPDATE_PATH? Would it be the proper Redux way? Or should I use something else?
Following Josh David Miller's advice, I made my route look like so:
<Route path="admin/profile/:id" component={Profile} />
Than my container got this method to get the profile from API:
componentWillMount() {
const { getProfile, dispatch } = this.props
getProfile(this.props.params.id)
}
And this to cleanup (without it I would have the previous profile display for split second on component load - before I hit API in componentWillMount)
componentWillUnmount() {
this.props.unmountProfile()
}
Update:
As an alternative to the cleanup, I'm considering using the Container Component Pattern. Basically have the outer component do the data fetching and passing the data to the inner component as a prop.

Categories