Launching interval after updating props in React.js - reactjs

I'd like to fire interval after backend data will come in as a prop.
Take a look at this chunk of code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getAdvert } from "../../actions/advert";
import './_advert.scss';
class Advert extends Component {
state = { counter: 0 };
componentDidMount() {
const { getAdvert } = this.props;
getAdvert();
}
componentWillReceiveProps(nextProps) {
const { counter } = this.state;
this.bannerInterval = setInterval(() => {
this.setState({ counter: counter === Object.keys(nextProps.banners).length - 1 ? 0 : counter + 1 });
}, 1000)
}
render() {
const { banners } = this.props;
const { counter } = this.state;
return (
<div className="advert__container">
<img src={banners[counter] && banners[counter].image_url} alt="advert" />
</div>
);
}
}
const mapStateToProps = ({ banners }) => {
return { banners };
};
const mapDispatchToProps = (dispatch) => {
return {
getAdvert: () => dispatch(getAdvert())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Advert);
So as you can see I tried to run it within componentWillReceiveProps method as I thought it might be proper place to be dependent on incoming props. But that won't work. I will run only once and interval will be repeating the same value.
Thanks for helping!

ComponentWillReceive props is extremely dangerous used in this way. You are istantiating a new interval every time a props is received without storing and canceling the previous one.
Also is not clear how do you increment counter, as I see the increment in your ternary will not increase the counter value incrementaly.
// This is an example, the lifeCylce callback can be componentWillReceive props
componentDidMount() {
const intervalId = setInterval(this.timer, 1000);
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: intervalId});
}
componentWillUnmount() {
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
}
timer = () => {
// setState method is used to update the state with correct binding
this.setState({ currentCount: this.state.currentCount -1 });
}

Related

change a static method for a functional component. I have been making class to functional but I have never done a static method yet

here is what the static method looks like, I want to change the class component to a functional component but functional components don't support it. I am still learning, any advice will be appreciated
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.security.validToken) {
setTimeout(() => {
const product_type = localStorage.getItem("types");
if (product_type === "imp") {
nextProps.history.push("/imported");
} else if (product_type === "branded") {
nextProps.history.push("/brands");
} else if (product_type === "imp,branded" || product_type === "branded,imp") {
nextProps.history.push("/imported-brands");
} else if (product_type === "local") {
nextProps.history.push("/local");
}
}, 1000);
}
Would be easier if you could share the whole component, or at least how/where you plan to manage your functional component's state. As said on this anwser:
This has a number of ways that it can be done, but the best way is situational.
Let's see how we could create a ProductsRouter functional component.
import React from 'react'
import { useHistory } from 'react-router'
export const ProductsRouter = ({ security }) => {
// our page state
const [productType, setProductType] = React.useState('')
// history object instance
const history = useHistory()
// our routing effect
React.useEffect(() => {
// if not authenticated, do nothing
if (!security.validToken) return
// update our state
setProductType(localStorage.getItem('types'))
// timeout function
const timer = setTimeout(() => {
if (productType === 'imp') {
history.push('/imported')
} else if (productType === 'branded') {
history.push('/brands')
} else if (productType === 'imp,branded' || productType === 'branded,imp') {
history.push('/imported-brands')
} else if (productType === 'local') {
history.push('/local')
}
}, 1000)
return () => clearTimeout(timer)
}, [])
return <pre>{JSON.stringify({ history }, null, 2)}</pre>
}
We could use a map to keep our code tidy and flexible. If there's no particular reason to have a 1000ms timeout, we could also call push instantly, as long as we have a validToken.
const typesMap = new Map([
['imp', '/imported'],
['branded', '/brands'],
['imp,branded', '/imported-brands'],
['branded,imp', '/imported-brands'],
['local', '/local'],
])
export const ProductsRouter = ({ security }) => {
const history = useHistory()
React.useEffect(() => {
if (!security.validToken) return
history.push(typesMap.get(localStorage.getItem('types')))
return () => {}
}, [security.validToken])
return <pre>{JSON.stringify({ history }, null, 2)}</pre>
}
Hope that helps! Cheers

Two components get called when page refreshes and the state is altered React

Basically, I have one component, let's call it component1 and a second component, which has been created by duplicating the first one called component2. I had to duplicate it, because some objects inside it had to be altered before sending them to the further components.
On one page I have an onClick event which triggers component1 which opens a modal and on another page, component2 is trigger the same as for the first one.
The problem occurs here, if I'm on the second page where the modal from component2 is opened and I refresh the page, both components are called, of course component1 is the first one called and the state is altered by this component which makes me not having the desired information in the second component.
As far as I understood, because of the fact that in both components, mapStateToProps is altering my state, both components are called. Not really sure though that I understood right.
Here is my component1 summary:
class LivePlayerModal extends React.Component {
constructor(props) {
super(props);
this.highlightsUpdated = null;
}
componentDidMount() {
const queryParam = UrlHelper.getParamFromLocation(IS_QUALIFICATION, window.location);
if (queryParam === null) {
ScoringLoader.subscribe(endpointNames.LIVE_SCANNER);
ScoringLoader.subscribe(endpointNames.PLAYERS);
ScoringLoader.subscribe(endpointNames.LEADERBOARD);
ScoringLoader.subscribe(endpointNames.COURSE);
ScoringLoader.subscribe(endpointNames.STATISTICS);
}
//TODO: make fixed fetch on timeout
this.fetchHighlights();
}
componentDidUpdate(prevProps) {
if (prevProps.playerId !== this.props.playerId) {
this.highlightsUpdated = null;
}
this.fetchHighlights();
}
componentWillUnmount() {
ScoringLoader.unsubscribe(endpointNames.LIVE_SCANNER);
ScoringLoader.unsubscribe(endpointNames.PLAYERS);
ScoringLoader.unsubscribe(endpointNames.LEADERBOARD);
ScoringLoader.unsubscribe(endpointNames.COURSE);
ScoringLoader.unsubscribe(endpointNames.STATISTICS);
}
render() {
const {
isOpen, scoringPlayer, isQualification, ...rest
} = this.props;
const highlightGroups = getHighlights(this.getCloudHighlights());
if (isQualification) {
return null;
}
return (
<ReactModal isOpen={isOpen} onCloseCb={this.hide}>
<div className="live-player">
{
scoringPlayer === undefined &&
<BlockPlaceholder minHeight={400}>
<BlockSpinner />
</BlockPlaceholder>
}
{
scoringPlayer === null &&
<LivePreMessage
model={{
title: '',
body: 'Player data coming soon'
}}
bemList={[bemClasses.LIGHT]}
/>
}
{
scoringPlayer &&
<LivePlayerLayout
{...rest}
scoringPlayer={scoringPlayer}
highlightGroups={highlightGroups}
/>
}
</div>
</ReactModal>
);
}
}
const mapStateToProps = (state, ownProps) => {
const isQualification = state.scoring.isQualification;
const { playerId } = ownProps;
const sitecorePlayers = state.scoring[endpointNames.PLAYERS];
const scoringLeaderboard = state.scoring[endpointNames.LEADERBOARD];
const getScoringPlayer = () => {
};
return ({
isQualification,
liveScanner: state.scoring[endpointNames.LIVE_SCANNER],
scoringLeaderboard,
scoringPlayer: getScoringPlayer(),
scoringStats: state.scoring[endpointNames.STATISTICS],
scoringCourse: state.scoring[endpointNames.COURSE],
sitecorePlayers: state.scoring[endpointNames.PLAYERS],
cloudMatrix: state.cloudMatrix
});
};
const mapDispatchToProps = (dispatch) => ({
fetchPlayerHighlights: (feedUrl) => dispatch(fetchFeed(feedUrl))
});
const LivePlayerCardContainer = connect(
mapStateToProps,
mapDispatchToProps
)(LivePlayerModal);
export default LivePlayerCardContainer;
Here is my component2 summary :
class QualificationLivePlayerModal extends React.Component {
constructor(props) {
super(props);
this.highlightsUpdated = null;
}
shouldComponentUpdate(nextProps) {
return nextProps.isQualification;
}
componentDidMount() {
ScoringLoader.subscribe(endpointNames.SUMMARY_FINAL);
ScoringLoader.subscribe(endpointNames.SUMMARY_REGIONAL);
ScoringLoader.subscribe(endpointNames.LIVE_SCANNER);
ScoringLoader.subscribe(endpointNames.PLAYERS);
ScoringLoader.subscribe(endpointNames.COURSE);
ScoringLoader.unsubscribe(endpointNames.LEADERBOARD);
ScoringLoader.unsubscribe(endpointNames.STATISTICS);
//TODO: make fixed fetch on timeout
this.fetchHighlights();
}
componentDidUpdate(prevProps) {
if (prevProps.playerId !== this.props.playerId) {
this.highlightsUpdated = null;
}
this.fetchHighlights();
}
componentWillUnmount() {
ScoringLoader.unsubscribe(endpointNames.SUMMARY_FINAL);
ScoringLoader.unsubscribe(endpointNames.SUMMARY_REGIONAL);
ScoringLoader.unsubscribe(endpointNames.COURSE);
ScoringLoader.unsubscribe(endpointNames.LEADERBOARD);
ScoringLoader.unsubscribe(endpointNames.STATISTICS);
}
render() {
const {
scoringPlayer, summaryFinal, ...rest
} = this.props;
const highlightGroups = getHighlights(this.getCloudHighlights());
const queryParam = UrlHelper.getParamFromLocation(IS_QUALIFICATION, window.location);
const open = (queryParam === 'true');
if (scoringPlayer !== undefined && scoringPlayer !== null) scoringPlayer.id = scoringPlayer.entryId;
return (
<ReactModal isOpen={open} onCloseCb={this.hide}>
<div className="qual-live-player">
{
scoringPlayer === undefined &&
<BlockPlaceholder minHeight={400}>
<BlockSpinner />
</BlockPlaceholder>
}
{
scoringPlayer === null &&
<LivePreMessage
model={{
title: '',
body: 'Player data coming soon'
}}
bemList={[bemClasses.LIGHT]}
/>
}
{
scoringPlayer &&
<LivePlayerLayout
{...rest}
scoringPlayer={scoringPlayer}
highlightGroups={highlightGroups}
/>
}
</div>
</ReactModal>
);
}
}
const mapStateToProps = (state, ownProps) => {
const isQualification = state.scoring.isQualification;
const { playerId, location } = ownProps;
const locationIdFromQueryParam = UrlHelper.getParamFromLocation(LOCATION_ID, window.location);
const locationId = location !== null ? location.locationId : locationIdFromQueryParam;
const sitecorePlayers = state.scoring[endpointNames.PLAYERS];
const summaryRegional = state.scoring[endpointNames.SUMMARY_REGIONAL];
const summaryFinal = state.scoring[endpointNames.SUMMARY_FINAL];
const scoringLeaderboard = getLeaderboardBasedOnLocation(locationId, summaryFinal, summaryRegional);
const currentRound = getCurrentRound(locationId, summaryFinal, summaryRegional);
const getScoringPlayer = () => {
};
return ({
isQualification,
liveScanner: state.scoring[endpointNames.LIVE_SCANNER],
scoringLeaderboard,
scoringPlayer: getScoringPlayer(),
scoringCourse: getScoringCourseFromQualificationFeed(),
sitecorePlayers: state.scoring[endpointNames.PLAYERS],
cloudMatrix: state.cloudMatrix,
});
};
const mapDispatchToProps = (dispatch) => ({
fetchPlayerHighlights: (feedUrl) => dispatch(fetchFeed(feedUrl))
});
const QualificationLivePlayerCardContainer = connect(
mapStateToProps,
mapDispatchToProps
)(QualificationLivePlayerModal);
export default QualificationLivePlayerCardContainer;
Basically, the problem i ve got here, is that in state.scoring I do not have the information for the endpoints present in the return statement of the render method before the page finishes the refresh process, which later on makes my app to break.
Hope I've been clear enough.
Is there a solution for waiting the endpoints to get called or even not loading the first component at all?

Redux - Fetch data, but render in another component

I'm currently fetching data in Component1, then dispatching an action to update the store with the response. The data can be seen in Component2 in this.props, but how can I render it when the response is returned? I need a way to reload the component when the data comes back.
Initially I had a series of functions run in componentDidMount but those are all executed before the data is returned to the Redux store from Component1. Is there some sort of async/await style between components?
class Component1 extends React.Component {
componentDidMount() {
this.retrieveData()
}
retrieveData = async () => {
let res = await axios.get('url')
updateParam(res.data) // Redux action creator
}
}
class Component2 extends React.Component {
componentDidMount() {
this.sortData()
}
sortData = props => {
const { param } = this.props
let result = param.sort((a,b) => a - b)
}
}
mapStateToProps = state => {
return { param: state.param }
}
connect(mapStateToProps)(Component2)
In Component2, this.props is undefined initially because the data has not yet returned. By the time it is returned, the component will not rerender despite this.props being populated with data.
Assuming updateParam action creator is correctly wrapped in call to dispatch in mapDispatchToProps in the connect HOC AND properly accessed from props in Component1, then I suggest checking/comparing props with previous props in componentDidUpdate and calling sortData if specifically the param prop value updated.
class Component2 extends React.Component {
componentDidMount() {
this.sortData()
}
componentDidUpdate(prevProps) {
const { param } = this.props;
if (prevProps.param !== param) { // <-- if param prop updated, sort
this.sortData();
}
}
sortData = () => {
const { param } = this.props
let result = param.sort((a, b) => a - b));
// do something with result
}
}
mapStateToProps = state => ({
param: state.param,
});
connect(mapStateToProps)(Component2);
EDIT
Given component code from repository
let appointmentDates: object = {};
class Appointments extends React.Component<ApptProps> {
componentDidUpdate(prevProps: any) {
if (prevProps.apptList !== this.props.apptList) {
appointmentDates = {};
this.setAppointmentDates();
this.sortAppointmentsByDate();
this.forceUpdate();
}
}
setAppointmentDates = () => {
const { date } = this.props;
for (let i = 0; i < 5; i++) {
const d = new Date(
new Date(date).setDate(new Date(date).getDate() + i)
);
let month = new Date(d).toLocaleString("default", {
month: "long"
});
let dateOfMonth = new Date(d).getDate();
let dayOfWeek = new Date(d).toLocaleString("default", {
weekday: "short"
});
// #ts-ignore
appointmentDates[dayOfWeek + ". " + month + " " + dateOfMonth] = [];
}
};
sortAppointmentsByDate = () => {
const { apptList } = this.props;
let dates: string[] = [];
dates = Object.keys(appointmentDates);
apptList.map((appt: AppointmentQuery) => {
return dates.map(date => {
if (
new Date(appt.appointmentTime).getDate().toString() ===
// #ts-ignore
date.match(/\d+/)[0]
) {
// #ts-ignore
appointmentDates[date].push(appt);
}
return null;
});
});
};
render() {
let list: any = appointmentDates;
return (
<section id="appointmentContainer">
{Object.keys(appointmentDates).map(date => {
return (
<div className="appointmentDateColumn" key={date}>
<span className="appointmentDate">{date}</span>
{list[date].map(
(apptInfo: AppointmentQuery, i: number) => {
return (
<AppointmentCard
key={i}
apptInfo={apptInfo}
/>
);
}
)}
</div>
);
})}
</section>
);
}
}
appointmentDates should really be a local component state object, then when you update it in a lifecycle function react will correctly rerender and you won't need to force anything. OR since you aren't doing anything other than computing formatted data to render, Appointments should just call setAppointmentDates and sortAppointmentsByDate in the render function.

React Sequential Rendering Hook

I've got some components which need to render sequentially once they've loaded or marked themselves as ready for whatever reason.
In a typical {things.map(thing => <Thing {...thing} />} example, they all render at the same time, but I want to render them one by one I created a hook to to provide a list which only contains the sequentially ready items to render.
The problem I'm having is that the children need a function in order to tell the hook when to add the next one into its ready to render state. This function ends up getting changed each time and as such causes an infinite number of re-renders on the child components.
In the examples below, the child component useEffect must rely on the dependency done to pass the linter rules- if i remove this it works as expected because done isn't a concern whenever it changes but obviously that doesn't solve the issue.
Similarly I could add if (!attachment.__loaded) { into the child component but then the API is poor for the hook if the children need specific implementation such as this.
I think what I need is a way to stop the function being recreated each time but I've not worked out how to do this.
Codesandbox link
useSequentialRenderer.js
import { useReducer, useEffect } from "react";
const loadedProperty = "__loaded";
const reducer = (state, {i, type}) => {
switch (type) {
case "ready":
const copy = [...state];
copy[i][loadedProperty] = true;
return copy;
default:
return state;
}
};
const defaults = {};
export const useSequentialRenderer = (input, options = defaults) => {
const [state, dispatch] = useReducer(options.reducer || reducer, input);
const index = state.findIndex(a => !a[loadedProperty]);
const sliced = index < 0 ? state.slice() : state.slice(0, index + 1);
const items = sliced.map((item, i) => {
function done() {
dispatch({ type: "ready", i });
return i;
}
return { ...item, done };
});
return { items };
};
example.js
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import { useSequentialRenderer } from "./useSequentialRenderer";
const Attachment = ({ children, done }) => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const delay = Math.random() * 3000;
const timer = setTimeout(() => {
setLoaded(true);
const i = done();
console.log("happening multiple times", i, new Date());
}, delay);
return () => clearTimeout(timer);
}, [done]);
return <div>{loaded ? children : "loading"}</div>;
};
const Attachments = props => {
const { items } = useSequentialRenderer(props.children);
return (
<>
{items.map((attachment, i) => {
return (
<Attachment key={attachment.text} done={() => attachment.done()}>
{attachment.text}
</Attachment>
);
})}
</>
);
};
function App() {
const attachments = [1, 2, 3, 4, 5, 6, 7, 8].map(a => ({
loaded: false,
text: a
}));
return (
<div className="App">
<Attachments>{attachments}</Attachments>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Wrap your callback in an aditional layer of dependency check with useCallback. This will ensure a stable identity across renders
const Component = ({ callback }) =>{
const stableCb = useCallback(callback, [])
useEffect(() =>{
stableCb()
},[stableCb])
}
Notice that if the signature needs to change you should declare the dependencies as well
const Component = ({ cb, deps }) =>{
const stableCb = useCallback(cb, [deps])
/*...*/
}
Updated Example:
https://codesandbox.io/s/wizardly-dust-fvxsl
Check if(!loaded){.... setTimeout
or
useEffect with [loaded]);
useEffect(() => {
const delay = Math.random() * 1000;
const timer = setTimeout(() => {
setLoaded(true);
const i = done();
console.log("rendering multiple times", i, new Date());
}, delay);
return () => clearTimeout(timer);
}, [loaded]);
return <div>{loaded ? children : "loading"}</div>;
};

Component illogically doesn't re-render on props change

I have a weird problem with React-Redux app. One of my components doesn't re-render on props change which is updated by action 'SET_WINNING_LETTERS'. github repo: https://github.com/samandera/hanged-man
setWord.js
const initialWordState = {
word: []
};
const setWinningLetters = (wordProps) => {
let {word, pressedKey} = wordProps;
for (let i = 0; i < word.length; i++) {
if (/^[a-zA-Z]$/.test(pressedKey) && word[i].letter.toUpperCase() == pressedKey) {
word[i].visible = true;
}
}
return {word};
}
const setWord = (state = initialWordState, action) => {
switch(action.type) {
case 'SET_WORD': return Object.assign({}, state, getWord(action.word));
case 'SET_WINNING_LETTERS': return Object.assign({}, state,
updateWord(action.wordProps));
}
return state;
}
export default setWord;
In Index.js in this function the actions are triggered
handleKeyPress(pressedKey) {
store.dispatch({
lettersProps: {
word:this.props.word,
pressedKey,
missedLetters: this.props.missedLetters
},
type: 'SET_MISSED_LETTERS'
});
store.dispatch ({
wordProps: {
word:this.props.word,
pressedKey
},
type: 'SET_WINNING_LETTERS'
});
this.showEndGame(this.props.word,this.props.missedLetters);
};
componentWillMount() {
fetchWord(this.statics.maxWordLength);
window.onkeydown = () =>
{this.handleKeyPress(String.fromCharCode(event.keyCode))};
}
And in PrimaryContent.js Winning and Missing Characetrs are rendered
import React from 'react';
import {connect} from 'react-redux';
import store from '../reducers/store';
import Hangedman from './Hangedman';
import AspectRatio from './AspectRatio';
import Puzzle from './Puzzle';
import MissedCharacters from './MissedCharacters';
const mapStateToProps = (store) => {
return {
word: store.wordState.word,
missedLetters: store.missedLettersState.missedLetters
}
}
class PrimaryContent extends React.Component {
constructor() {
super();
}
renderDisabledPuzzles(amount){
return Array.from({length: amount}, (value, key) => <AspectRatio parentClass="disabled" />)
}
renderLetters(word) {
return word.map(function(letterObj, index) {
let space = (letterObj.letter==' ' ? "disabled": '')
return(
<AspectRatio parentClass={space} key={"letter" + index}>
<div id={"letter" + index}>{letterObj.visible ? letterObj.letter : ''}</div>
</AspectRatio>
)
}) ;
}
render() {
let disabledCount = this.props.puzzles - this.props.word.length;
let disabledPuzzles = this.renderDisabledPuzzles(disabledCount);
let WinningLetters = this.renderLetters(this.props.word);
return (
<div className="ratio-content primary-content">
<Hangedman/>
<MissedCharacters missedLetters={this.props.missedLetters}/>
<Puzzle>
{disabledPuzzles}
{WinningLetters}
</Puzzle>
</div>
);
}
}
export default connect(mapStateToProps)(PrimaryContent);
MissedCharacters works well while {WinningLetters} doesn't.
The action 'SET_MISSED_LETTERS' works perfect, while 'SET_WINNING_LETTERS' works only when 'SET_MISSED_LETTERS' gets updated. It means when I press one or more letter that wins they won't display until I press the letter that is missing. When I press the missing letter the component that is parent for both missing and winning letters re-renders. I was trying to pass props to PrimaryContent from it's parent but I get the same. I tried to separate {WinningLetters} in it's own component wit access to redux store but it works even worse and stops updating even when MissedCharacters updates. Can you detect where I've made a mistake?

Resources