I am introducing a form into the /add-employee
path, which captures the data into the main App.js file. After filling in the fields, changing the path I would like the state to be cleared to the original settings.
I tried to enter another <Route>
that will capture the location and if it is a path other than /add-employee
state will be changed, but it causes an inifinite loop
In the add-employee
pathway the form of adding an employee. After submitting the form, the employee is displayed in the /employees
path.
//App.js
class App extends Component {
state = {
employeesList: [],
id: 0,
firstName: '',
lastName: '',
email: '',
phone: '',
accountNumber: '',
rate: '',
location: '',
};
render() {
const contextElements = {
...this.state,
handleDate: this.handleDate,
handleSubmit: this.handleSubmit,
};
return (
<Router>
<AppContext.Provider value={contextElements}>
<div className="app">
<Navigation />
<Footer />
<div className="content">
<Switch>
<Route path="/" exact component={InstructionPage} />
<Route
path="/add-employee"
component={AddEmployee}
render={props => console.log(props.location.pathname)}
/>
<Route path="/employees" component={Employees} />
<Route path="/ranking" component={Ranking} />
<Route component={ErrorPage} />
</Switch>
</div>
</div>
</AppContext.Provider>
</Router>
);
}
}
Checking the route for clearing the state would be very tight coupling that is better avoided.
Instead we can have the component AddEmployee
clear the state on componentWillUnmount
Something like:
class AddEmployee extends Component {
componentWillUnmount {
this.props.clearForm();
}
}
On defining the routes:
<Route
path="/add-employee"
render={props => <AddEmployee {...props} clearForm={this.clearState}/>}
/>
In this.clearState()
, clear the state values that you have to.