Include Modal functionality in React Higher-Order Component - javascript

I created the below HOC which I can use to wrap a React component to add 2 inactivity timers: the first to show the user a warning; the other to log them out. I got the idea from here and it seems to work pretty well. That is, I can add withTimer functionality to a component by wrapping it like this:
export default withTimer(DragDropContext(HTML5Backend)(App));
The problem is the warning alert box halts the event loop (as alert boxes apparently always do), so the logout function is never reached.
I believe a modal (e.g., from react-bootstrap) would solve this, as it presumably would not halt the event loop, thus the logout would occur as intended if the user is still idle after the warning alert.
How would I change the below HOC to use a modal for the warning instead of an alert box? Is this possible? That is, can a HOC that's used to wrap another component include a component itself (i.e., the modal) so as to keep it decoupled from the wrapped component itself?
import React from 'react';
import { Modal } from 'react-bootstrap';
const withTimer = (WrappedComponent) => {
class WithTimer extends React.Component {
constructor(props) {
super(props);
this.state = {
warningTime: 5000,
signoutTime: 10000
};
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];
for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}
this.setTimeout();
}
clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};
setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};
resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};
warn = () => {
window.alert('You will be logged out soon. Click to stay logged in.');
};
logout = () => {
window.alert('You are being logged out!');
// log the user out here
};
render() {
console.log('HOC');
return <WrappedComponent {...this.props.children} />;
}
}
return WithTimer;
};
export default withTimer;

If you wanted to use a Modal, you could do something like this:
Live Demo
withTimer.js
import React from 'react';
import MyModal from './MyModal';
const withTimer = (WrappedComponent) => {
class WithTimer extends React.Component {
constructor(props) {
super(props);
this.state = {
warningTime: 5000,
signoutTime: 10000,
showModal: false,
modalMessage: "",
modalButtonText: "",
};
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];
for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}
this.setTimeout();
}
clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};
setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};
resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};
onModalClick = () => {
this.setState({
showModal: false,
}, () => this.resetTimeout())
}
warn = () => {
this.setState({
modalButtonText: "Stay Logged In",
modalHeader: "Warning!",
modalMessage: 'You will be logged out soon. Click to stay logged in.',
showModal: true,
});
};
logout = () => {
this.setState({
modalButtonText: "Ok",
modalHeader: "Session Timed Out",
modalMessage: 'You are being logged out!',
showModal: true,
});
// log the user out here
};
render() {
console.log('HOC');
return (
<>
<MyModal
show={this.state.showModal}
modalMessage={this.state.modalMessage}
modalHeader={this.state.modalHeader}
buttonText={this.state.modalButtonText}
onButtonClick={this.onModalClick} />
<WrappedComponent {...this.props.children} />
</>
);
}
}
return WithTimer;
};
export default withTimer;
MyModal.js
import React, { useState } from "react";
import { Modal, Button } from "react-bootstrap";
function MyModal({ show = false, modalMessage, modalHeader, onButtonClick, buttonText }) {
const handleClick = event => {
onButtonClick(event);
}
return (
<Modal show={show} onHide={handleClick} animation={false}>
<Modal.Header closeButton>
<Modal.Title>{modalHeader}</Modal.Title>
</Modal.Header>
<Modal.Body>{modalMessage}</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleClick}>
{buttonText}
</Button>
</Modal.Footer>
</Modal>
);
}
export default MyModal;

Yes, you can render any components you'd like in the HOC. So in your case you can render a <Modal/>.
Of course, whether the modal is displayed or not is dynamic, so that's a perfect job for the component's state to come into play. Use conditional statements in your render function to either render or not render your modal.
import React from 'react';
import { Modal } from 'react-bootstrap';
const withTimer = (WrappedComponent) => {
class WithTimer extends React.Component {
constructor(props) {
super(props);
this.state = {
showWarning: false,
showLogout: false,
warningTime: 5000,
signoutTime: 10000
};
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];
for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}
this.setTimeout();
}
clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};
setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};
resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};
warn = () => {
this.setState({ showWarning: true });
};
logout = () => {
this.setState({ showLogout: true });
// log the user out here
};
render() {
let modal;
if (this.state.showLogout) {
modal = <Modal>...</Modal>;
} else if (this.state.showWarning) {
modal = <Modal>...</Modal>;
} else {
modal = null;
}
return <React.Fragment>
<WrappedComponent {...this.props.children} />
{ modal }
</React.Fragment>;
}
}
return WithTimer;
};
export default withTimer;

Related

onClick passing in tests, but failing when physically clicked

This is my Accordion component
import React, {Component, Fragment} from 'react';
import ArrowTemplate from "./ArrowTemplate";
import ContentTemplate from "./ContentTemplate";
class Accordion extends Component {
constructor(props) {
super(props);
this.state = {isAccordionExpanded: false};
this.foldAccordion = this.foldAccordion.bind(this);
this.expandAccordion = this.expandAccordion.bind(this);
}
expandAccordion() {
console.log(1);
this.setState({isAccordionExpanded: true});
}
foldAccordion() {
console.log(2);
this.setState({isAccordionExpanded: false});
}
render() {
const {state} = this;
const {isAccordionExpanded} = state;
if (isAccordionExpanded === false) {
return (
<Fragment>
<ArrowTemplate
aria={`aria-expanded="true"`}
onClick={this.expandAccordion}
direction={'down'}
color={'black'}
styles={'background:yellow'}
/>
</Fragment>
);
} else if (isAccordionExpanded === true) {
return (
<Fragment>
<ArrowTemplate
aria={`aria-expanded="true"`}
onClick={this.foldAccordion}
color={'black'}
direction={'up'}
/>
<ContentTemplate/>
</Fragment>
);
}
}
}
export default Accordion;
this is the ArrowTemplate
import React from "react";
import BlackDownArrowSVG from './svgs/black-down-arrow.svg';
import WhiteDownArrowSVG from './svgs/white-down-arrow.svg';
import styled from 'styled-components';
import PropTypes from 'prop-types';
ArrowTemplate.propTypes = {
color: PropTypes.string.isRequired,
direction: PropTypes.string.isRequired,
styles: PropTypes.string,
aria: PropTypes.string.isRequired,
};
function ArrowTemplate(props) {
const {color, direction, styles, aria} = props;
const StyledArrowTemplate = styled.img.attrs({
src: color.toLowerCase() === "black" ? BlackDownArrowSVG : WhiteDownArrowSVG,
aria,
})`
${direction.toLowerCase() === "up" ? "translate: rotate(180deg)" : ""}
${styles}
`;
return <StyledArrowTemplate/>;
}
export default ArrowTemplate;
And here are my related tests
describe("<Accordion/>",
() => {
let wrapper;
beforeEach(
() => {
wrapper = shallow(
<Accordion/>
);
}
);
it('should have one arrow at start',
function () {
expect(wrapper.find(ArrowTemplate)).toHaveLength(1);
}
);
it('should change state onClick',
function () {
wrapper.find(ArrowTemplate).simulate("click");
expect(wrapper.state().isAccordionExpanded).toEqual(true);
}
);
it('should call FoldAccordionMock onClick',
function () {
wrapper.setState({isAccordionExpanded: true});
wrapper.find(ArrowTemplate).simulate("click");
expect(wrapper.state().isAccordionExpanded).toEqual(false);
}
);
it('should display content if isAccordionExpanded = true',
function () {
wrapper.setState({isAccordionExpanded: true});
expect(wrapper.find(ContentTemplate).exists()).toEqual(true);
}
);
it('should hide content if isAccordionExpanded = false',
function () {
expect(wrapper.find(ContentTemplate).exists()).toEqual(false);
}
);
}
);
So the problem is that when I tun the tests .simulate(click) seems to work, and all tests pass. But when I click the component myself, nothing happens. Not even a console log. Changing the onClick to onClick={()=>console.log(1)} doesn't work either. Any ideas what's wrong?
StyledArrowTemplate inner component does not know anything about onClick.
ArrowTemplate doesn't know what onClick means, it's just another arbitrary prop to it.
But, if you do as #ravibagul91 said in their comment, you should pass down onClick again, StyledArrowTemplate might know what onClick means.
So just add <StyledArrowTemplate onClick={props.onClick}/>
Accordion Component
import React, { Component, Fragment } from "react";
import ArrowTemplate from "./ArrowTemplate";
import ContentTemplate from "./ContentTemplate";
class Accordion extends Component {
constructor(props) {
super(props);
this.state = { isAccordionExpanded: false };
}
toggleAccordian = () => {
console.log(1);
this.setState({ isAccordionExpanded: !isAccordionExpanded });
};
render() {
const { state } = this;
const { isAccordionExpanded } = state;
if (isAccordionExpanded) {
return (
<Fragment>
<ArrowTemplate
aria={`aria-expanded="true"`}
onClick={() => this.toggleAccordian()}
color={"black"}
direction={isAccordionExpanded ? "up" : "down"}
styles={`background:{isAccordionExpanded ? 'yellow' : ''}`}
/>
<ContentTemplate />
</Fragment>
);
}
}
}
export default Accordion;

How to change state when in other page click?

in project i have 3 page
1)i need when i click in button 'Next' in page 1 redirect to page 2 and show toast Component in page2
2)when click'Next' in page 2 redirect to page 3
3)and when click button 'back' in page 3 redirect to page 2 but not show toast in page2,
How do slove this chalange, redirect work correctly i have problem in show toast or not show in page 2
---page1---
class page1 extends Component {
handleSubmit = (e) => {
this.props.history.push('/page2');
};
render() {
return (
<Fragment>
<Button
title={"Next"}
onClick={this.handleSubmit}
/>
</Fragment>
);
}
}
---page2 - i write state for toast in componentDidMount f---
class page2 extends Component {
constructor(props) {
super(props);
this.state = {
showToast: false,
messageToast: '',
levelToast: 'success',
}
}
componentDidMount() {
this.setState({
showToast: true,
messageToast: 'Ok',
levelToast: 'success',
}, () => {
setTimeout(() => this.setState({showToast: false}), 3000)
})
}
handleSubmit = () => {
this.props.history.push('/page3');
};
render() {
return (
<Fragment>
<Button
title={"Next"}
onClick={this.handleSubmit}
/>
</Fragment>
);
}
}
--page3---
class page3 extends Component {
handleBack = (e) => {
e.preventDefault();
this.props.history.push('/page2');
};
render() {
return (
<Fragment>
<Button
type={"close"}
title={"back"}
id={'b'}
onClick={this.handleBack}
/>
</Fragment>
);
}
}
Assuming you're using React Router, the easiest way would be to use the second argument that goes into the the history.push function. You could do something like:
Page1.js
class Page1 extends Component {
handleSubmit = (e) => {
this.props.history.push('/page2', {showToast: true});
// the second argument sets a state value that can be accessed in the `Page2` component
};
render() {
return (
<Fragment>
<Button
title={"Next"}
onClick={this.handleSubmit}
/>
</Fragment>
);
}
}
Page2.js
class Page2 extends Component {
constructor(props) {
super(props);
this.state = {
showToast: false,
messageToast: '',
levelToast: 'success',
}
}
componentDidMount() {
// this is the `state` argument in the `handleSubmit` function on Page1
const shouldShowToast = this.props.location.state && this.props.location.state.showToast
this.setState({
showToast: shouldShow,
messageToast: 'Ok',
levelToast: 'success',
}, () => {
setTimeout(() => this.setState({showToast: false}), 3000)
})
}
...
...
}
'Page3.js`
class Page3 extends Component {
handleBack = (e) => {
e.preventDefault();
this.props.history.push('/page2', {showToast: false}); // set the location state.showToast to `false` this time.
};
...
...
}
Hope that helped!

React : Updated values is not coming in React-popup

I am working on React-popup but I face some problem . I set condition if user select 3rd option then I am updating state value . State value is updated, When I console it in render then it showing updated value but when I want to use it in React-PopUp updated value is not working . I need to re-render a content on pop-up form if state is get updated . I am new please help me .
Note: PopUp form will be show on click
Code
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import MyCalendar from 'react-big-calendar';
import CustomToolbar from './toolbar';
import Popup from 'react-popup';
import Input from './input';
import axios from 'axios'
import moment from 'moment';
import { fetchEvents, createEvent, updateEvent, deleteEvent } from '../../actions/calendar';
// Setup the localizer by providing the moment (or globalize) Object to the correct localizer.
const localizer = MyCalendar.momentLocalizer(moment); // or globalizeLocalizer
class Calendar extends Component {
constructor(){
super();
this.state={
isCustomer:false,
}
}
onChangeHandler = ev => {
this.setState(
{isCustomer:ev.target.value === "viewing"},
() => { console.log(this.state.isCustomer)
})
}
componentDidMount() {
this.props.fetchEvents();
}
//RENDER SINGLE EVENT POPUP CONTENT
renderEventContent(slotInfo) {
const date = moment(slotInfo.start).format('MMMM D, YYYY');
return (
<div>
<p>Date: <strong>{date}</strong></p>
<p>Subject: {slotInfo.taskChage}</p>
<p>Time : {slotInfo.time}</p>
<p>Date : { slotInfo.date}</p>
<p>Notes : {slotInfo.notes}</p>
<p>User Id : {slotInfo.userId}</p>
</div>
);
}
//ON SELECT EVENT HANDLER FUNCTION
onSelectEventHandler = (slotInfo) => {
console.log("New Applicaiton ", this.state.isCustomer)
Popup.create({
title: slotInfo.title,
content: this.renderEventContent(slotInfo),
buttons: {
right: [{
text: 'Edit',
className: 'info',
action: function () {
Popup.close(); //CLOSE PREVIOUS POPUP
this.openPopupForm(slotInfo); //OPEN NEW EDIT POPUP
}.bind(this)
}, {
text: 'Delete',
className: 'danger',
action: function () {
//CALL EVENT DELETE ACTION
this.props.deleteEvent(slotInfo.id);
Popup.close();
}.bind(this)
}]
}
});
}
//HANDLE FUNCITON ON SELECT EVENT SLOT
onSelectEventSlotHandler = (slotInfo) => {
this.openPopupForm(slotInfo); //OPEN POPUP FOR CREATE/EDIT EVENT
}
//POPUP-FORM FUNCTION FOR CREATE AND EDIT EVENT
openPopupForm = (slotInfo) => {
let newEvent = false;
let popupTitle = "Update Event";
if(!slotInfo.hasOwnProperty('id')) {
slotInfo.subject = null;
slotInfo.taskType = null;
slotInfo.time=null;
slotInfo.date=null;
slotInfo.notes=null;
slotInfo.userId=null;
popupTitle = "Add task to Diary";
newEvent = true;
}
let titleChange = function (value) {
slotInfo.subject = value;
};
let taskChange = function (value) {
slotInfo.taskType = value;
};
let timeChange = function (value) {
slotInfo.time = value;
};
let dateChnage = function ( value){
slotInfo.date=value;
};
let notesChange = function ( value){
slotInfo.notes=value;
};
let userId = function ( value){
slotInfo.userId=value;
};
Popup.create({
title: popupTitle,
content: <div>
<Input fieldName="subject" onChange={titleChange} placeholder="Subject" />
<select name="taskType" onChange={this.onChangeHandler}>
<option vlaue="no">Task Type</option>
<option value="meeting">Meeting</option>
<option value="followup">Follow Up</option>
<option value="viewing">Viewing</option>
<option value="reminder">Reminder</option>
<option value="other">Other</option>
</select>
{this.state.isCustomer===true && <input defaultValue="Hi customer :)"></input>}
<Input fieldName="time" onChange={timeChange} placeholder="Time"/>
<Input fieldName="date" onChange={dateChnage} placeholder="Date"/>
<Input fieldName="notes" onChange={notesChange} placeholder="Notes"/>
<Input fieldName="userId" onChange={userId} placeholder="User Id"/>
</div>,
buttons: {
left: ['cancel'],
right: [{
text: 'Save',
className: 'success',
action: function () {
//CHECK THE ID PROPERTY FOR CREATE/UPDATE
if(newEvent) {
this.props.createEvent(slotInfo); //EVENT CREATE ACTION
} else {
this.props.updateEvent(slotInfo); //EVENT UPDATE ACTION
}
Popup.close();
}.bind(this)
}]
}
});
}
//EVENT STYLE GETTER FOR SLYLING AN EVENT ITEM
eventStyleGetter(event, start, end, isSelected) {
let current_time = moment().format('YYYY MM DD');
let event_time = moment(event.start).format('YYYY MM DD');
let background = (current_time>event_time) ? '#DE6987' : '#8CBD4C';
return {
style: {
backgroundColor: background
}
};
}
render() {
return (
<div className="calendar-container">
<MyCalendar
popup
selectable
localizer={localizer}
defaultView={MyCalendar.Views.MONTH}
components={{toolbar: CustomToolbar}}
views={['month']}
style={{height: 600}}
events={this.props.events}
eventPropGetter={(this.eventStyleGetter)}
onSelectEvent={(slotInfo) => this.onSelectEventHandler(slotInfo)}
onSelectSlot={(slotInfo) => this.onSelectEventSlotHandler(slotInfo)}
/>
<Popup />
</div>
);
}
}
function mapStateToProps(state) {
return {
events: state.events
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
fetchEvents,
createEvent,
updateEvent,
deleteEvent
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Calendar);
Try to use react inbuild method componentDidUpdate(). The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied
import React, { Component } from "react";
import ReactDom from "react-dom";
import { Modal, Button, Row, Col, Form } from "react-bootstrap";
class PopupModal extends React.Component {
popupShown = true;
componentWillMount() {
}
componentDidUpdate() { //called when state update in parent component
this.setState({ modalData: null });
this.setState({ modalData: this.props.modalData});
this.popupShown = true;
}
state = {
modalData: this.props.modalData //getting data for the modal from parent
};
onHidePopup = () => {
this.setState({ modalData: null });
this.popupShown = false;
};
render() {
if (this.popupShown == true) {
return (
<Modal
show={this.popupShown}
onHide={this.onHidePopup}
>
<Modal.Header closeButton>
<Modal.Title id="modalTitle">Model header</Modal.Title>
</Modal.Header>
<Modal.Body>
Model body comes here
</Modal.Body>
<Modal.Footer>
<p>Hello I am Footer</p>
</Modal.Footer>
</Modal>
);
} else {
return <div />;
}
}
}
export default PopupModal;

Console.log() after setState() doesn't return the updated state

I've created a simple todo list to learn react and i'm trying to add some additional features. At the moment i'm trying to add buttons that toggle the list of items, so it either shows all the tasks or just those that are completed.
I've written a function to change the state of my visabilityFilter so I can later use this to toggle the items in the list, but it isn't behaving how it should be.
I console log the visabilityFilter variable but it always shows the wrong state before changing to the correct state. e.g. the 'show all' button will console log 'show completed' then if you press it again it will console log 'show all'
App.js
import React, { Component } from 'react';
import './App.css';
import TodoList from './components/TodoList.js'
import VisabilityFilter from './components/VisabilityFilter.js'
export const SHOW_ALL = 'show_all'
export const SHOW_COMPLETED = 'show_completed'
class App extends Component {
constructor (props) {
super(props)
this.state = {
inputValues: {
'newTodo': ''
},
todos: [
{
task: 'My First Todo',
completed: false
}
],
visabilityFilter: SHOW_ALL
}
this.addTodo = this.addTodo.bind(this)
this.handleInputChange = this.handleInputChange.bind(this)
this.handleKeyUp = this.handleKeyUp.bind(this)
this.toggleCompleted = this.toggleCompleted.bind(this)
this.removeTodo = this.removeTodo.bind(this)
this.checkCompleted = this.checkCompleted.bind(this)
this.setVisabilityFilter = this.setVisabilityFilter.bind(this)
}
handleInputChange (e) {
const { inputValues } = this.state
const { id, value } = e.target
this.setState({
inputValues: {
...inputValues,
[id]: value
}
})
}
handleKeyUp (e) {
var code = e.key
if(code === 'Enter') {
this.addTodo(e);
}
}
toggleCompleted (e, index) {
const { todos } = this.state
todos[index].completed = !todos[index].completed
todos.sort((a, b) => b.completed - a.completed)
this.setState({ todos })
}
removeTodo (e, index) {
const { todos } = this.state
this.setState ({ todos: todos.filter((todo, i) => i !== index) })
}
addTodo (e) {
const { todos, inputValues } = this.state
const { dataset } = e.target
if (inputValues[dataset.for] === '') return
const newTodo = { task: inputValues[dataset.for], completed: false }
todos.push(newTodo)
this.setState({
todos,
inputValues: { ...inputValues, [dataset.for]: '' }
})
}
checkCompleted (e, index) {
const { todos } = this.state
return { todos } && todos[index].completed
}
setVisabilityFilter (e) {
const { visabilityFilter } = this.state
const { dataset } = e.target
this.setState({
visabilityFilter: dataset.for
})
console.log ({ visabilityFilter })
}
render() {
const { todos, inputValues, visabilityFilter } = this.state
return (
<div className="App">
<TodoList
todos={todos}
inputValues={inputValues}
addTodo={this.addTodo}
handleInputChange={this.handleInputChange}
removeTodo={this.removeTodo}
toggleCompleted={this.toggleCompleted}
handleKeyUp={this.handleKeyUp}
checkCompleted={this.checkCompleted}
/>
<VisabilityFilter setVisabilityFilter={this.setVisabilityFilter} />
</div>
);
}
}
export default App;
VisabilityFilter.js
import React from 'react'
import { func } from 'prop-types'
import { SHOW_ALL, SHOW_COMPLETED } from '../App'
const VisabilityFilter = props => {
return (
<div>
<button data-for={SHOW_COMPLETED} onClick={ props.setVisabilityFilter } >
Show Completed Tasks
</button>
<button data-for={SHOW_ALL} onClick={ props.setVisabilityFilter }>
Show All Tasks
</button>
</div>
)
}
VisabilityFilter.propTypes = {
setVisabilityFilter: func.isRequired
}
export default VisabilityFilter
setState() is async (React docs), so the state changes won't be applied immediately. If you want to log out the new state,setState() takes in a function as the second argument and performs that function when the state is updated. So:
this.setState({
abc: xyz
},
() => console.log(this.state.abc),
)
Or you can also use componentDidUpdate(), which is recommended
In the functional components, you can use useEffect to track changes in state.
useEffect(() => {
console.log(someState);
},[someState);

How can I update High Order Component

I created array of routing in ReactJS
const routes = [
{ id: 0, path: '/', view: Home, parent: 0 },
{ id: 1, path: '/a', view: Home2, parent: 0 },
{ id: 2, path: '/b', view: Home3, parent: 1 }
]
Created HOC withAuth which should back to parent routing when user isn't logged. When i going to route (as not logged) - its ok and withAuth back me to parent route, but when i am on route and logout page isn't refresh and I am stay on route for logged users.
import React, { Component } from "react";
import AuthHelper from "./AuthHelper";
export default function withAuth(AuthComponent) {
const Auth = new AuthHelper();
class AuthWrapped extends Component {
constructor(props) {
super(props);
this.state = {
confirm: null,
loaded: false
};
}
checkLogged = () => {
if (!Auth.loggedIn()) {
const parent = this.props.parent;
const obj = this.props.routes
.filter(v => v.id === parent);
this.props.history.replace(obj[0].path);
} else {
try {
const confirm = Auth.getConfirm();
this.setState({
confirm: confirm,
loaded: true
});
} catch (err) {
Auth.logout();
this.props.history.replace("/");
}
}
}
componentDidMount() {
this.checkLogged();
}
render() {
if (this.state.loaded) {
if (this.state.confirm) {
return (
<AuthComponent
history={this.props.history}
confirm={this.state.confirm}
/>
);
} else {
return null;
}
} else {
return null;
}
}
};
return AuthWrapped;
}
I believe that you are using the authentication system the wrong way
In React everything should exist in a hierarchical manner.
In your case, you have an Auth state that would change and when the loggedIn state changes, everything should re-render. the correct way to do this is using the Context API to handle the logged in state so when the state changes, the whole screen would re-render
here is the solution to your problem:
AuthContext.js
const AuthContext = React.createContext();
export class AuthProvider extends React.Component {
state = {
isLoggedIn: false,
};
login = (username, password) => {
someLoginRequestToServer(username, password).then(response => {
this.setState({
isLoggedIn: response.isLoggedIn,
});
});
};
logout = () => {
someLogoutRequestToServer().then(() => {
this.setState({ isLoggedIn: false });
});
};
render() {
return (
<AuthContext.Provider
value={{
loggedIn: this.state.isLoggedIn,
login: this.login,
logout: this.logout,
}}>
{this.props.children}
</AuthContext.Provider>
);
}
}
export const AuthConsumer = AuthContext.Consumer;
SomeCustomAuthComponent
class CustomAuthComponent extends React.Component {
render() {
return (
<AuthConsumer>
{({ loggedIn, login, logout }) => (
<div>
<p>You Are {loggedIn ? 'Logged in' : 'Logged out'}</p>
<button onClick={loggedIn ? () => logout() : () => login('abcd', '12345')} />
</div>
)}
</AuthConsumer>
);
}
}
Or you can use the redux for state management and react-redux as it uses the react Context API under the hood.
hope this helps you! :)
the problem lays here
componentDidMount() {
this.checkLogged();
}
you're checking if the user is logged only when the component is mounted (after the instantiation). you should be checking it every time the page updates, you have to identify a way to handle this mechanism for example by using the componentDidUpdate hook.
export default function withAuth(AuthComponent) {
const Auth = new AuthHelper();
class AuthWrapped extends Component {
constructor(props) {
super(props);
this.state = {
confirm: null,
loaded: false
};
}
checkIsNotLogged = () => {
const parent = this.props.parent;
const obj = this.props.routes
.filter(v => v.id === parent);
this.props.history.replace(obj[0].path);
}
checkLogged = () => {
if (!Auth.loggedIn()) {
this.checkIsNotLogged();
} else {
try {
const confirm = Auth.getConfirm();
this.setState({
confirm: confirm,
loaded: true
});
} catch (err) {
Auth.logout();
this.props.history.replace("/");
}
}
}
componentDidMount() {
this.checkLogged();
}
componentDidUpdate() {
// do not call here the checkLogged method otherwise you could trigger an infinite loop
this.checkIsNotLogged();
}
render() {
if (this.state.loaded) {
if (this.state.confirm) {
return (
<AuthComponent
history={this.props.history}
confirm={this.state.confirm}
/>
);
} else {
return null;
}
} else {
return null;
}
}
};
return AuthWrapped;
}

Categories

Resources