Redux setState called after component unmounted - reactjs

I'm building a React/Redux app with 3 main Components -
Instructions, StoryFeed and Quiz which i'm trying to cycle through for
4 Rounds (3 + 1 practice).
I have a Clock Component (that's nested within the StoryFeed
Component) and it's set to move to the Quiz Component when the timer
hits zero. However, it seems to be calling setState after it's been
unmounted and giving the infinite 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.
I can't figure out how to prevent this. Here's the code below for the Clock Component:
import React from 'react'
import PropTypes from 'prop-types'
import ReactInterval from 'react-interval'
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0,
timed: props.timed,
counting: true
}
this.tick = this.tick.bind(this)
}
reset() {
this.setState({
counting: true,
count: this.state.count + 1
})
}
componentWillUnmount() {
this.setState({ counting: false }, () => this.props.complete())
}
tick() {
const { count, timed, counting } = this.state
if (count + 1 > timed && counting) {
this.componentWillUnmount()
} else {
this.reset();
}
}
render() {
return (
<div className="clock alert alert-warning">
<ReactInterval
timeout={1000}
enabled={this.props.timed > 1 && this.state.count < this.props.timed}
callback={() => this.tick()}
/>
<span>{this.state.timed - this.state.count}</span>
</div>
)
}
}
Clock.propTypes = {
timed: PropTypes.number,
complete: PropTypes.func
}
export default Clock
And here's the parent Component StoryFeed code:
import React from 'react'
import Marquee from './Marquee'
import * as stories from '../stories'
import Clock from './Clock'
import { chunk, now } from '../utils'
import PropTypes from 'prop-types'
class StoryFeed extends React.Component {
constructor(props) {
super(props)
this.state = {
text: stories.example,
currentTest: 1,
count: 0,
timed: props.timed,
selected: []
}
this.storyLoad.bind(this)
this.select = this.select.bind(this)
this.isSelected = this.isSelected.bind(this)
}
componentDidMount() {
document.body.classList.add('mosaic-full-screen')
this.storyLoad();
}
componentWillUnmount() {
document.body.classList.remove('mosaic-full-screen')
}
select(id) {
if (this.state.selected.find(s => s.id == id)) return
this.setState({
selected: [...this.state.selected, { id, time: now() }]
})
}
isSelected(id) {
return this.state.selected.find(j => j.id === id)
}
storyLoad(state) {
switch (this.state.currentTest){
case 1:
this.setState({text: stories.example});
console.log(this.state.currentTest)
break;
case 2:
this.setState({text: stories.colleagues});
break;
case 3:
this.setState({text: stories.aroomforthenight});
break;
case 4:
this.setState({text: stories.thepromotion});
break;
}
};
reset() {
this.clock &&
this.clock.reset(4, () => {
this.setState({
counting: true
})
})
}
render() {
const { enterAnswers, id, show, timed } = this.props
return (
<div className="story">
<div className='container'>
<Marquee text={this.state.text.join(' - ')} loop={false} hoverToStop={true} />
</div>
<div className="controls">
{timed && (
<Clock
timed={timed}
complete={() => enterAnswers(id, this.state.selected, now())}
/>
)}
</div>
</div>
)
}
}
StoryFeed.propTypes = {
timed: PropTypes.number,
enterAnswers: PropTypes.func,
id: PropTypes.number,
show: PropTypes.oneOf(['window', 'jigsaw'])
}
export default StoryFeed
The other answers to this question seem to be case specific

You can set a method attribute on unmount and then only update the state if this attribute is not set. For example:
componentWillUnmount() {
this.unmounted = true;
}
...
someMethod() {
if (!this.unmounted) this.setState{...}
}

one way to resolve this issue it as follows
class X extends Component {
mounted = false
ss = (...args) => {
this.mounted && this.setState(...args)
}
componentDidMount(){
this.mounted = true
}
componentWillUnMount(){ // or componentDidUnmount
this.mounted = false
}
}
now you can use this.ss instead of this.setState or alternatively you can check the this.mounted before setting the state
I'm not sure this is the best solution, but it does resolve the issue

Related

React: setState with Countdown

I have a state counter in my main App.js class. Also I have a Countdown.js, which updates the counter of his parent class every time he has finished. But i get an Error, when the timer finished once. Also, state counter jumps from 0 to 2 and not from 0 to 1...
Warning: Cannot update during an existing state transition (such as within `render`).
How can i get rid of this error? Or do you have a solution how to count++, when the timer is finished?
My class App.js:
import React from "react"
import "./App.css"
import Countdown from "./Countdown.js"
class App extends React.Component {
constructor() {
super();
this.state = {
counter: 0
};
this.count = this.count.bind(this);
}
count() {
this.setState(prevState => ({
count: prevState.counter++
}));
}
render() {
return (
<div className="window">
<p>{this.state.counter}</p>
<Countdown count={this.count} />
</div>
);
}
}
export default App
My Countdown.js
import React from "react";
import CountDown from "react-countdown";
class CountdownQuestion extends React.Component {
constructor() {
super();
this.state = {
time: 3000
};
}
render() {
const renderer = ({ seconds, completed }) => {
if (completed) {
this.props.count();
return <h2>Zeit abgelaufen</h2>;
} else {
return <h3>{seconds}</h3>;
}
};
return (
<CountDown date={Date.now() + this.state.time} renderer={renderer} />
);
}
}
export default CountdownQuestion;
Well, it's exactly like the error says. You can't update state (like in your count() function) during a render. You're probably better of using the onComplete hook.
class CountdownQuestion extends React.Component {
constructor() {
super();
this.state = {
time: 3000
};
}
render() {
// Removing this.props.count() from this function also keeps it more clean and focussed on the rendering.
const renderer = ({ seconds, completed }) => {
if (completed) {
return <h2>Zeit abgelaufen</h2>;
} else {
return <h3>{seconds}</h3>;
}
};
return (
<CountDown
date={Date.now() + this.state.time}
onComplete={this.props.count} // <-- This will trigger the count function when the countdown completes.
renderer={renderer}
/>
);
}
}

how manage proper way to implement Countdown Timer for two players in react js?

I am a newbie for react js. how to manage two Countdown timers first start and second is stop after 5-second interval second start and first stop.
it work for single Clock successful but add two clocks then first only start and not stop while second not start I don't know how do this ?.
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
isActive: true
};
}
componentDidMount() {
this.intervalId = setInterval(() => {
this.randomCallObject();
}, 5000);
}
randomCallObject() {
this.setState({
Active: !this.state.isActive
});
}
render() {
let clock= {
time: 150,
isActive:this.state.isActive
}
let clock2= {
time: 100,
isActive:!this.state.isActive
}
return (
<div className="container">
<Clcok ClockData={clock}/>
<Clcok ClockData={clock2}/>
</div>
);
}
}
import React, { Component } from "react";
const TOTAL_MINUTES = 60;
export default class ClockComponent extends Component {
constructor(props) {
super(props);
this.state = {
time: props.ClockData.time,
isActive: props.ClockData.isActive
};
}
componentDidMount() {
const { isActive } = this.state;
if (isActive === true) {
this.intervalId = setInterval(() => {
const { time } = this.state;
if (time > 0) {
this.setState({
time: time - 1
});
}
}, 1000);
}
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
render() {
const { time } = this.state;
let minutes ="" + Math.floor((time % (TOTAL_MINUTES * TOTAL_MINUTES))/ TOTAL_MINUTES);
let seconds = "" + Math.floor(time % TOTAL_MINUTES);
if (isNaN(minutes) || isNaN(seconds)) {
return null;
}
if (minutes.length === 1) {
minutes = `0${minutes}`;
}
if (seconds.length === 1) {
seconds = `0${seconds}`;
}
return (
<div className="row">
<div className="col-md-1">
<div>
{minutes}:{seconds}
</div>
</div>
</div>
);
}
}
when clock data comes from props so take simple objects when isActive flag is true then clock timer on when isActive false then timer stop
To learn how to handle setInterval with React, I suggest you read the following blog post by Dan Abramov:
Making setInterval Declarative with React Hooks
In it, he explains how to use setInterval using React Hooks and also how to do it using a class component. On the post, there is also a link to a CodeSandbox example where you can see it in action.
What I did was create another CodeSandbox where you can see how you could apply this example to run multiple timers:
https://codesandbox.io/embed/timers-l6me1
I've used React Hooks in the example because they don't require a lot of code.
I hope it helps.
edit #1
Here is an example of a Counter component taken directly from the mentioned article, and adapted to fit the latter example.
class Counter extends React.Component {
state = {
count: 0,
delay: 1000,
isRunning: true
};
constructor(props) {
super(props);
this.state = { ...this.state, ...props };
}
componentDidMount() {
this.interval = setInterval(this.tick, this.state.delay);
}
componentDidUpdate(prevProps, prevState) {
if (prevState.delay !== this.state.delay) {
this.startInterval();
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
startInterval = () => {
clearInterval(this.interval);
this.interval = setInterval(this.tick, this.state.delay);
console.log(this.interval);
};
tick = () => {
this.setState({
count: this.state.count + 1
});
};
handleDelayChange = e => {
this.setState({ delay: Number(e.target.value) });
};
toggleCounter = () => {
console.log(this.state.isRunning);
if (this.state.isRunning) {
clearInterval(this.interval);
} else {
this.startInterval(this.state.delay);
}
this.setState({
count: 0,
isRunning: !this.state.isRunning
});
};
render() {
const {
state: { isRunning, delay, count },
toggleCounter,
handleDelayChange
} = this;
return (
<>
<h1>{count}</h1>
<input value={delay} onChange={handleDelayChange} />
<button onClick={toggleCounter}>{isRunning ? "stop" : "start"}</button>
</>
);
}
}

How to setState in ComponentDidMount

I have something strange with a react app,
I used it in a django project and want to re-use it in a laravel project but it doesn't want to work properly ...
Here is the code of my component :
import React from "react"
import {LeftControl, RightControl, CountControl } from './controls'
import {Slide} from './slide'
import axios from "axios"
export default class Slider extends React.Component {
constructor(props){
super(props);
this.state = {
items : [],
active:0
}
}
componentDidMount() {
axios.get('/coming')
.then((res)=>{
this.setState({ items: res.data, active: 0})
});
setInterval( () => {
this.goToNextSlide()
},5000);
}
goToPrevSlide = () => {
const n = this.state.items.length
if (this.state.active == 0) {
this.setState({active : n-1})
} else {
this.setState({active: this.state.active - 1})
}
}
goToNextSlide = () => {
const n = this.state.items.length
if (this.state.active == n-1){
this.setState({active : 0})
} else {
this.setState({active: this.state.active +1})
}
}
render(){
return(
<div className="slider">
<div className="slider__controls">
<CountControl active={this.state.active} length={this.state.items.length} />
<LeftControl goToPrevSlide={this.goToPrevSlide} />
<RightControl goToNextSlide={this.goToNextSlide}/>
</div>
<div className="slider__items">
{
this.state.items
.map((item, i) => (
<Slide active={this.state.active} index={i} key={i} id={item.id} first_name={item.first_name} last_name={item.last_name} role={item.role} conference_date={item.conference_date} thumbnail={item.thumbnail} />
))
}
</div>
</div>
)
}
}
Uncommenting the setState in componentDidMount raise the following error :
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in Slider
The component works well on my other project ...
Anyone would have an idea what is the problem ?
Thank you
As riwu commented, you get the warning because the axios call and timer you define in componentDidMount try to set the state of Slider after it has been unmounted. Do the following instead:
export default class Slider extends React.Component {
...
constructor(props) {
super(props);
this._isMounted = false;
this.state = {
items : [],
active:0,
}
}
componentDidMount() {
this._isMounted = true;
axios.get('/coming')
.then((res) => {
if (this._isMounted) {
this.setState({ items: res.data, active: 0})
}
});
this.timer = setInterval(() => {
this.goToNextSlide();
}, 5000);
}
componentWillUnmount() {
this._isMounted = false;
clearInterval(this.timer);
}
...
}

Reactjs. Counter of renders

How to make counter of renders the child component in parent?
I have 2 components Widget (parent) and Message(child). I passed counter from child to parent and trying to set getting value from child set to state. And I getting err: Maximum update depth exceeded.
There is child component Message:
import React, { Component } from "react";
export default class Message extends React.Component {
constructor(props) {
super(props);
this.changeColor = this.changeColor.bind(this);
this.changeCount = this.changeCount.bind(this);
this.state = { h: 0, counter: 0 };
}
changeColor = () => {
this.setState(state => ({
h: Math.random()
}));
};
changeCount = () => {
this.setState(state => ({
counter: ++state.counter
}));
};
componentDidUpdate(prevProps) {
this.props.getColor(this.color);
this.changeCount();
this.props.getCount(this.state.counter);
}
render() {
const { children } = this.props;
const { s, l, a } = this.props.color;
this.color = `hsla(${this.state.h}, ${s}%, ${l}%, ${a})`;
return (
<p
className="Message"
onClick={this.changeColor}
style={{ color: this.color }}
>
{children}
</p>
);
}
}
There is parent component:
import React, { Component } from "react";
import Message from "./Message/Message";
export default class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
color: {
s: 30,
l: 60,
a: 1
},
counter: 0
};
}
getCount = count => this.setState(state => ({
counter: state.counter
}));
getColor = color => {
console.log(`the color is ${color}`);
};
render() {
const counter = this.state.counter;
return (
<div>
<Message
getColor={this.getColor}
getCount={this.getCount}
color={this.state.color}
>
{undefined || `Hello World!`}
</Message>
{counter}
</div>
);
}
}
What I do wrong?
The answer by #Yossi counts total renders of all component instances. This solution counts how many renderes and re-renders an individual component has done.
For counting component instance renders
import { useRef } from "react";
export const Counter = props => {
const renderCounter = useRef(0);
renderCounter.current = renderCounter.current + 1;
return <h1>Renders: {renderCounter.current}, {props.message}</h1>;
};
export default class Message extends React.Component {
constructor() {
this.counter = 0;
}
render() {
this.counter++;
........
}
}
In order to count the number of renders, I am adding a static variable to all my components, and incrementing it within render().
For Class components:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
let renderCount = 0;
export class SampleClass extends Component {
render() {
if (__DEV__) {
renderCount += 1;
console.log(`${this.constructor.name}. renderCount: `, renderCount);
}
return (
<View>
<Text>bla</Text>
</View>
)
}
}
For functional Components:
import React from 'react';
import { View, Text } from 'react-native';
let renderCount = 0;
export function SampleFunctional() {
if (__DEV__) {
renderCount += 1;
console.log(`${SampleFunctional.name}. renderCount: `, renderCount);
}
return (
<View>
<Text>bla</Text>
</View>
)
}
The componentDidUpdate is calling this.changeCount() which calls this.setState() everytime after the component updated, which ofcourse runs infinitely and throws the error.
componentDidUpdate(prevProps) {
this.props.getColor(this.color);
// Add a if-clause here if you really want to call `this.changeCount()` here
// For example: (I used Lodash here to compare, you might need to import it)
if (!_.isEqual(prevProps.color, this.props.color) {
this.changeCount();
}
this.props.getCount(this.state.counter);
}

ReactJS. Infinity loop

I'am getting props from child in getCount function. And set it prop into state. Than i try set it in component and get infinity loop. How can i fix that?
There is code of parent component:
import React, { Component } from "react";
import Message from "./Message/Message";
export default class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
color: {
s: 30,
l: 60,
a: 1
},
counter: 0
};
}
getCount = count => this.setState(state => ({
counter: count
}));
getColor = color => {
console.log(`the color is ${color}`);
};
render() {
const counter = this.state.counter;
return (
<div>
<Message
getColor={this.getColor}
getCount={this.getCount}
color={this.state.color}
>
{undefined || `Hello World!`}
</Message>
{counter}
</div>
);
}
}
child:
import React, { Component } from "react";
export default class Message extends React.Component {
constructor(props) {
super(props);
this.changeColor = this.changeColor.bind(this);
this.state = { h: 0 };
this.counter = 0;
}
changeColor = () => {
this.setState(state => ({
h: Math.random()
}));
};
componentDidUpdate(prevProps) {
this.props.getColor(this.color);
this.props.getCount(this.counter);
}
render() {
this.counter++;
const { children } = this.props;
const { s, l, a } = this.props.color;
this.color = `hsla(${this.state.h}, ${s}%, ${l}%, ${a})`;
return (
<p
className="Message"
onClick={this.changeColor}
style={{ color: this.color }}
>
{children}
</p>
);
}
}
The problem lies in your Message component.
You are using getCount() inside your componentDidUpdate() method. This causes your parent to re-render, and in turn your Message component to re-render. Each re-render triggers another re-render and the loop never stops.
You probably want to add a check to only run the function if the props have changed. Something like:
componentDidUpdate(prevProps) {
if(prevProps.color !== this.props.color) {
this.props.getColor(this.color);
this.props.getCount(this.counter);
}
}
This will keep the functionality you need, but prevent, not only the infinity-loop, but also unnecessary updates.

Resources