React-Redux Infinite loop because of possibly changing state [duplicate] - javascript

This question already has answers here:
Why do event handlers need to be references and not invocations?
(2 answers)
Closed 5 years ago.
Good afternoon,
In my class PageList I want to add a function that changes the state on click. However when I insert this function into the a button that doesnt even get clicked the browser starts a never ending loop changing the state of currentpage.
Even though I have read the docs about components this seems strange behaviour. The behaviour accurs when addPage button is clicked.
Thanks in advance!
PageList:
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import Page from '../components/Page.jsx';
import {addPage} from '../actions/addPage.js'
import {nextPage} from '../actions/nextPage.js'
import RaisedButton from 'material-ui/RaisedButton';
import _ from 'lodash';
class PageList extends Component {
constructor(props){
super(props);
this.state = {
currentpage : 0,
};
}
nextPage(){
this.setState({currentpage: this.state.currentpage+1});
}
renderList() {
if(this.props.item){
return (
<div>
<RaisedButton label="Next Page" onClick={this.nextPage()}></RaisedButton>
<Page key={this.state.currentpage} index={this.state.currentpage}>
{this.props.item.title}
{this.props.item.desc}
</Page>
</div>
);
}else{
return(
<p>No Pages</p>
)
}
}
render() {
return (
<div>
<RaisedButton label="Add new Page" onClick={() => this.props.addPage("Titel Page", "Page Beschrijving")}></RaisedButton>
<ul>
{this.renderList()}
</ul>
</div>
);
}
}
// Get apps state and pass it as props to PageList
// > whenever state changes, the PageList will automatically re-render
function mapStateToProps(state, ownProps) {
return {
pageList: state.pageList,
item: _.find(state.pages, 'id', ownProps.currentpage)
};
}
// Get actions and pass them as props to to PageList
// > now PageList has this.props.selectPage
function matchDispatchToProps(dispatch){
return bindActionCreators({addPage: addPage, nextPage: nextPage}, dispatch);
}
// We don't want to return the plain PageList (component) anymore, we want to return the smart Container
// > PageList is now aware of state and actions
export default connect(mapStateToProps, matchDispatchToProps)(PageList);

You're calling the nextPage function on each render instead of passing it to onClick.
Change onClick={this.nextPage()} with onClick={() => this.nextPage()}

There is a little error:
<RaisedButton label="Next Page" onClick={this.nextPage}>
</RaisedButton>
otherwise this.nextPage() is called right when it is rendered.

Related

Push to new route without any further actions on the component

We use an external componet which we don't control that takes in children which can be other components or
used for routing to another page. That component is called Modulation.
This is how we are currently calling that external Modulation component within our MyComponent.
import React, {Fragment} from 'react';
import { withRouter } from "react-router";
import { Modulation, Type } from "external-package";
const MyComponent = ({
router,
Modulation,
Type,
}) => {
// Need to call it this way, it's how we do modulation logics.
// So if there is match on typeA, nothing is done here.
// if there is match on typeB perform the re routing via router push
// match happens externally when we use this Modulation component.
const getModulation = () => {
return (
<Modulation>
<Type type="typeA"/> {/* do nothing */}
<Type type="typeB"> {/* redirect */}
{router.push('some.url.com')}
</Type>
</Modulation>
);
}
React.useEffect(() => {
getModulation();
}, [])
return <Fragment />;
};
export default withRouter(MyComponent);
This MyComponent is then called within MainComponent.
import React, { Fragment } from 'react';
import MyComponent from '../MyComponent';
import OtherComponent1 from '../OtherComponent1';
import OtherComponent2 from '../OtherComponent2';
const MainComponent = ({
// some props
}) => {
return (
<div>
<MyComponent /> {/* this is the above component */}
{/* We should only show/reach these components if router.push() didn't happen above */}
<OtherComponent1 />
<OtherComponent2 />
</div>
);
};
export default MainComponent;
So when we match typeB, we do perform the rerouting correctly.
But is not clean. OtherComponent1 and OtherComponent2 temporarily shows up (about 2 seconds) before it reroutes to new page.
Why? Is there a way to block it, ensure that if we are performing router.push('') we do not show these other components
and just redirect cleanly?
P.S: react-router version is 3.0.0

Delete images if the user is leaving the component React

I have form with a drag and drop component where I can upload images, after this I send these pictures with axios to my backend and save it on server side and then re-render it in a preview mode. My problem is, that if a user uploads some pictures and after that he switches to another page without submitting the form the added pictures are staying on my server side for no reason.
So the question: I want to check inside my component if a user is leaving, show a prompt and if he clicks on the OK button I want to delete all the added pictures from my backend before leaving. How can I detect this?
My simplified snippet:
function MyComp(props) {
const [Images,setImages] = useState([]) // in this array I store the recieved image's URL
const [isBlocking,setIsBlocking] = useState(true) // used for prompt
const handleSubmit = (event) => {
event.preventDefault();
setIsBlocking(false)
}
return(
<Grid container className={classes.mainGrid} direction="row" spacing={2}>
<Grid item xs={4} xl={4}>
<Prompt when={isBlocking} message="There are unsaved datas. Are you sure you want to leave?"/>
<form className={classes.form} onSubmit={handleSubmit}>
... somecode
</Grid>
</Grid>
)
}
export default MyComp
Thanks in advance
Inside React Function Component you can call the prompt when the user is trying to leave , i.e when the component is unmounting
In Class Component of React you can use React componentWillUnmount() and in Function Component You can use useEffect cleanup function
Code for Function Component
import React, { useEffect } from "react";
import { Link } from "react-router-dom";
export default function Home(props) {
useEffect(() => {
return function cleanup() {
alert("unmounting");
//call api and execute your code here
};
}, []);
return (
<div>
<Link to="/home">
On Click I will unmount this component and go to /home
</Link>
</div>
</Link>
);
}
Code for Class Component
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Test extends Component {
componentWillUnmount() {
alert('unmounting component');
//call your code here
}
render() {
return (
<div>
<Link to='/home'>
On Click I will unmount this component and go to /home
</Link>
</div>
);
}
}
You can check this codesandbox if you want any ref
When you leave the page, the component method componentWillUnmount() fires. I don't recall how this behaves if you were to simply close the browser window as opposed to just navigating away, nor do I recall how you can escape it and stay on the component, but that should at least be a good starting point for you. Obviously you'd have to do a class extending React.Component for this one instead of a straight function.

Render a new Component without using router

I've created an application to React, and when it starts, the App component is rendered. I would like that when the user clicks on a button or link, the button or link has to be in the App component when clicking on that link, another component will be rendered but not inside the App component but only the new component will be rendered in the same URL. As for this new component, it has to have a similar button so that when the user clicks, only the App component is rendered and this component that the user has clicked on is not rendered, only the App component.
I do not know if I explained myself correctly. Ask me any question if you need some clarification.
My App component is the following:
import React, { Component } from 'react';
import Touch from './Touch';
import '../App.css';
class App extends Component{
render() {
return(
<div>
<div className="wrapper" >
<button >NewComponent</button><NewComponent />???
<h1>Google Cloud Speech with Socket.io</h1>
<p id="ResultText"><span className="greyText">No Speech to Text yet</span></p>
</div>
<div className="buttonWrapper" >
<button className="btn" id="startRecButton" type="button"> Start recording</button>
<button className="btn" id="stopRecButton" type="button"> Stop recording</button>
</div>
</div>
);
}
}
export default App
My index.js is the following:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
import App from './components/App.js';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
If you really don't want to use react-router you will need to store a value in the component's state and change the rendering method to reflect which button was pressed. If you want each of those component to include the button you need to switch, do the following :
class App extends Component {
constructor(props){
super(props);
this.state = {renderA: false,};
}
handleClick = (event) => {
this.setState((prevState) => ({renderA: !prevState.renderA}));
};
render = () => {
return(
<div>
{this.state.renderA ?
<ComponentA handleClick={this.handleCLick}/>:
<ComponentB handleClick={this.handleCLick}/>
}
</div>
);
};
} export default App;
// ComponentA
class ComponentA extends Component {
render = () => {
return(
<div>
// what you want inside your first page here
<button onClick={this.props.handleClick}
</div>
);
}
} export default ComponentA;
// ComponentB
class ComponentB extends Component {
render = () => {
return(
<div>
// what you want inside your second page here
<button onClick={this.props.handleClick}
</div>
);
}
} export default ComponentB;
But using react-router might also suits your case, and if you are going to write a large app, you should use it instead of rendering differents children components within the same one, based on users inputs.
If the URL stay the same, I don't think React-Router might help you.
If you want that App Component is not loaded, I think you should create two more Component, a Wrapper one, and the new component you want to display (from now on newComponent). What I suggest is:
Creating a property isButtonClicked inside the state of the Wrapper Component;
Creating a function handleButtonClick() inside the Wrapper Component:
handleButtonClick() => {
let isButtonClicked = !this.state.isButtonClicked;
this.setState({ isButtonClicked });
}
In the render() method of the Wrapper component, you write something like this:
render() {
if (this.state.isButtonClicked)
return <App />
else
return <NewComponent />
}
Then, in both App and NewComponent, if you click on the button, you call the this.props.handleButtonClick(), which will lead to a change of the state of Wrapper Component, therefore to a change of what is shown on the screen.

How come I can't navigate to the next page?

I'm trying to navigate to another component upon the Food Truck button being clicked. In the nextPage() function, I'm trying to make that happen but it just keeps throwing me an error.
How can I go from page to the next when clicking a button?
Note: I want to go to a totally different page, not stay on the same page.
import React, { Component } from "react";
import fire from "../../config/Fire";
import classes from "./Home.css";
import Aux from "../../hoc/Aux";
import Taco from "../../components/taco/Taco";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
taco: {}
};
}
nextPage() {
return this.state.taco ? <Taco /> : <Home />;
}
render() {
return (
<Aux>
<h1 className={classes.ChooseTruck}>Choose your favorite truck!</h1>
<button
type="button"
className="btn btn-outline-primary btn-lg btn-block"
onClick={this.nextPage}
>
Food Truck
</button>
</Aux>
);
}
}
export default Home;
Hey guys I figured out what I did wrong :D Here's how you conditionally render if anyone else needs a reference on how to do so :D.
-I had to bind taco in the constructor i.e. this.taco = this.taco.bind(this);
-Create a state called flag and set it equal to false i.e. this.state {flag: false}
-Inside the nextPage() method, I had to set the state to true in order to be used later i.e. this.setState({flag: true});
-Inside render(), I set a variable called flag equal to the state of flag i.e. const flag = this.state.flag; which WAS initially false but afterwards set to true upon clicking the button which invokes nextPage()
-Finally, we check if flag is set equal true. If it's true, then return the component I'm trying to navigate to which's <Taco/>
import React, {Component} from 'react';
import fire from '../../config/Fire';
import classes from './Home.css';
import Aux from '../../hoc/Aux';
import Taco from '../../components/taco/Taco';
class Home extends Component {
constructor(props) {
super(props);
this.taco = this.taco.bind(this);
this.state = {
flag: false
}
}
nextPage() {
this.setState({flag: true});
}
render() {
const flag = this.state.flag;
if(flag) {
return <Taco/>;
}
return (
<Aux>
<h1 className={classes.ChooseTruck}>Choose your favorite truck!</h1>
<button
type="button"
className="btn btn-outline-primary btn-lg btn-block"
onClick={this.nextPage}>Food Truck
</button>
</Aux>
);
}
}
export default Home;
It is not possible to navigate to different screen with just pure React library. If you only use React without any navigation libraries, it means that you can only have a SPA(Single Page Application).
Try to research this github link https://github.com/ReactTraining/react-router. Or just navigate to the official documentation in here https://reacttraining.com/react-router/.

Add loader on button click in react/redux application

I'm trying to add a Loader as Higher-Order-Component on button click in react/redux application.
Already have working Loader component and styling, just need to set logic when button is clicked show loader and hide existing button.
Button component:
import React from 'react'
import '../../../styles/components/_statement-print.scss';
import Loader from './Loader';
const StatementPrint = (props) => {
return (
<div>
<button
className="print-statement-button"
onClick={props.handleStatementPrint}>PRINT
</button>
</div>
);
};
export default Loader(StatementPrint);
Loader:
import React, { Component} from 'react';
import '../../../styles/components/_loader.scss';
const Loader = (WrappedComponent) => {
return class Loader extends Component {
render() {
return this.props.handleStatementPrint // Where must be logic when to show loader or existing button component
? <button className="loader-button">
<div className="loader">
<span className="loader-text">LOADING...</span>
</div>
</button>
: <WrappedComponent {...this.props} />
}
}
}
export default Loader;
In Loader component i added comment where need to write logic when to set loader or button.
I followed this example: ReactCasts - Higher Order Components
I searched a lot of examples but most of them shows how to set loader then is data is fetching, but in my case i just need to show then onClick method is triggered.
So how to set logic when onClick method is fired? Is this is a good aproach? Also it will be better to try acomplish this doing with redux state, but don't know how to do this.
Any help will be appreciated.
You will have to make small modifications to achieve what you want.
The wrapper component Loader can have a isLoading state, on the basis of which you can decide whether to show the loader span or the wrapped component.
This state isLoading can be updated by the wrapped component by passing showLoader function as a prop.
Button component
import React from 'react'
import '../../../styles/components/_statement-print.scss';
import Loader from './Loader';
const StatementPrint = ({handleStatementPrint, showLoader}) => {
return (
<div>
<button
className="print-statement-button"
onClick={() => {
showLoader();
handleStatementPrint();
}}>
PRINT
</button>
</div>
);
};
export default Loader(StatementPrint);
Loader
import React, { Component} from 'react';
import '../../../styles/components/_loader.scss';
const Loader = (WrappedComponent) => {
return class Loader extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: false
}
this.showLoader = this.showLoader.bind(this);
}
showLoader() {
this.setState({isLoading: true});
}
render() {
return this.state.isLoading
? <button className="loader-button">
<div className="loader">
<span className="loader-text">LOADING...</span>
</div>
</button>
: <WrappedComponent
{...this.props}
showLoader={this.showLoader}
/>
}
}
}
export default Loader;
EDIT
Since handleStatementPrint was required to be called, I have updated the click handler to include that function.
Also using de-structuring to avoid typing props repeatedly. See here for more info.
Just some external state is needed.
If you can't have external state (eg isLoading) than you could pass a function into a loader hoc which will derive isLoading from current props
Example: https://codesandbox.io/s/8n08qoo3j2

Categories

Resources