I'm having a issue with a component I've built. One value (inclVal) must be larger than another (exclVal) if both are entered. I wanted to run the function that handles this with a setTimeout() so that it wouldn't update for a second after the props stop changing to ensure it wouldn't change the value the user is entering while she is entering it. To this end, I put in a clearTimeout() in an else block to prevent the function from executing if the props change so as to make it redundant. The problem is that clearTimeout() isn't working for some reason and the update function is running whenever the if block is entered, even though the else block is being entered within the timeout interval.
The component is a stateless functional component and is using redux for state management. I've read a bunch on how to make these things work, but nothing seems to be helping. Any help is appreciated!
Here is the code:
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import SelectPickerPulldown from '../../components/SelectPickerPulldown'
import TextInput from '../../components/TextInput'
import { odOptions } from '../../config/'
import { setODProperty } from '../../actions/odAnalyzerActions'
import { getConversion, getGreaterVal } from '../../utils/'
const InclusionExclusionOptions = ({ name,
analysisPoint,
paths,
exclVal,
exclUnit,
inclVal,
inclUnit,
getVal,
getUnit,
setSafeInclVal,
}) => {
const disabled = analysisPoint !== null || paths ? false : true
let inclEntryTimer = null
const exclCompare = getConversion(exclUnit)(exclVal)
const inclCompare = getConversion(inclUnit)(inclVal)
if (exclVal > 0 && inclVal > 0 && exclCompare > inclCompare) {
const safeInclVal = getGreaterVal(exclVal, exclUnit, inclUnit)
console.log('entering timeout');
inclEntryTimer = setTimeout( () => {
console.log('dispatching timeout action');
setSafeInclVal(safeInclVal)
}, 1000)
}
else {
console.log('clearing timeout');
clearTimeout(inclEntryTimer)
inclEntryTimer = null
}
return (
<div className="form-group" >
<h4>Inclusion/Exclusion Options</h4>
<ul className={name}>
<li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
<p>Exclusion Radius</p>
<div className="radius-setting">
<TextInput
type="number"
name="exclVal"
value={exclVal}
onChange={getVal}
/>
<SelectPickerPulldown
value={'exclUnit'}
options={odOptions.units}
selected={exclUnit}
getSelected={getUnit}
/>
</div>
</li>
<li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
<p>Inclusion Radius</p>
<div className="radius-setting">
<TextInput
type="number"
name="inclVal"
value={inclVal}
onChange={getVal}
/>
<SelectPickerPulldown
value={'inclUnit'}
options={odOptions.units}
selected={inclUnit}
getSelected={getUnit}
/>
</div>
</li>
</ul>
</div>
)
}
InclusionExclusionOptions.propTypes = {
name: PropTypes.string,
exclVal: PropTypes.number,
exclUnit: PropTypes.string,
inclVal: PropTypes.number,
inclUnit: PropTypes.string,
getVal: PropTypes.func,
getUnit: PropTypes.func,
}
const mapStateToProps = (state, ownProps) => {
const name = 'inclusion-exclusion-options'
const { analysisPoint,
paths,
exclVal,
exclUnit,
inclVal,
inclUnit } = state.odAnalyzerState
return {
name,
analysisPoint,
paths,
exclVal,
exclUnit,
inclVal,
inclUnit,
}
}
const mapDispatchToProps = dispatch => {
return {
getUnit: option => dispatch(setODProperty(option)),
getVal: (e, name) => dispatch(setODProperty({[name]: parseInt(e.target.value)})),
setSafeInclVal: safeInclVal => dispatch(setODProperty({inclVal: safeInclVal}))
}
}
export default connect(
mapStateToProps,
mapDispatchToProps)(InclusionExclusionOptions)
Here is the updated code with a class component using componentDidUpdate():
class InclusionExclusionOptions extends React.Component{
constructor(props){
super(props)
this.inclEntryTimer = null
}
componentDidUpdate(props){
const { exclVal,
exclUnit,
inclVal,
inclUnit,
} = this.props
const exclCompare = getConversion(exclUnit)(exclVal)
const inclCompare = getConversion(inclUnit)(inclVal)
if (!!exclVal && !!inclVal && exclCompare > inclCompare) {
const safeInclVal = getGreaterVal(exclVal, exclUnit, inclUnit)
console.log('entering timeout')
this.inclEntryTimer = setTimeout( () => {
console.log('dispatching timeout action');
this.props.setSafeInclVal(safeInclVal)
}, 3000)
}
else {
console.log('clearing timeout');
clearTimeout(this.inclEntryTimer)
this.inclEntryTimer = null
}
}
render() {
const { name,
analysisPoint,
paths,
exclVal,
exclUnit,
inclVal,
inclUnit,
getVal,
getUnit,
} = this.props
const disabled = analysisPoint !== null || paths ? false : true
return (
<div className="form-group" >
<h4>Inclusion/Exclusion Options</h4>
<ul className={name}>
<li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
<p>Exclusion Radius</p>
<div className="radius-setting">
<TextInput
type="number"
name="exclVal"
value={exclVal}
onChange={getVal}
/>
<SelectPickerPulldown
value={'exclUnit'}
options={odOptions.units}
selected={exclUnit}
getSelected={getUnit}
/>
</div>
</li>
<li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
<p>Inclusion Radius</p>
<div className="radius-setting">
<TextInput
type="number"
name="inclVal"
value={inclVal}
onChange={getVal}
/>
<SelectPickerPulldown
value={'inclUnit'}
options={odOptions.units}
selected={inclUnit}
getSelected={getUnit}
/>
</div>
</li>
</ul>
</div>
)
}
}
Per Brandon's suggestion, I was able to get the timeout cleared by simply clearing it before redeclaring it. I broke out a clear timeout function as
clearInclEntryTimer(){
clearTimeout(this.inclEntryTimer)
this.inclEntryTimer = null
}
then called it at the top of the if block and in the else block. That worked well. Thanks for the help!
The actual problem is that everytime your component renders, it generates a new instance of inclEntryTimer (and all other local variables) and so there's no way for a subsequent call to ever clear the timeout started in a previous call.
The conceptual problem is that your component is stateful, not stateless. Your requirements are such that the component needs to track time as state (specifically the timer). Change your stateless component to a traditional stateful component and you'll be able to store the timer id as a property of the class instance. You can then use componentDidUpdate(prevProps) life cycle event to clear the timeout if the conditions are met.
Update:
Based on what you've tried, the real problem is that you aren't clearing the old timers on every prop change. So think about what happens if the props change and you start a timer, the props change again and it is still higher so you start a 2nd timer and never clear the first, the props change again and you start a 3rd timer and so on. Finally the props change and you stop the last timer. But the first 5 timers are still running. So you should clear the existing timer everytime you start a new one.
But if you step back from the problem slightly...you don't need to implement this pattern yourself. What you are doing is something known as "debouncing". So use someone else's debounce algorithm.
Here's how to do it with lodash:
import debounce from 'lodash/debounce';
export default class Component from React.Component {
componentDidMount() {
this.correctValues(this.props);
}
componentDidUpdate() {
this.correctValues(this.props);
}
componentWillUnmount() {
// prevent the debounced method from running after we unmount
this._unmounted = true;
}
render() {
return <div>...</div>;
}
// we use debounce to essentially only run this function 3000 ms after
// it is called. If it gets called a 2nd time, stop the first timer
// and start a new one. and so on.
correctValues = debounce(props => {
// make sure we are still mounted
if (!this._unmounted) {
// need to correct the values!
if (props.a < props.b) {
props.setCorrectValue(props.a);
}
}
}, 3000);
}
Related
I am new to React, Mobx stack. I bumped into a problem where my Store does not reflect its value immediately after the first call. when I make the second call, it returns the first value. I am unable to understand why it happens since I have a long way to go in React, Mobx stack.
My Store Class
export default class ServiceTemplateStore {
loadingInitial = false;
serviceTemplateDetail: any | undefined;
constructor() {
makeAutoObservable(this)
}
setLoadingInitial = (state: boolean) => {
this.loadingInitial = state;
}
get getServiceTemplateDetail() {
return this.serviceTemplateDetail;
}
loadServiceTemplateDetail = async (id: string) => {
this.loadingInitial = true;
try {
const serviceTemplateDetail = await agent.serviceTemplateDetail.details(id);
runInAction(() => {
console.log("Service loaded");
this.serviceTemplateDetail = serviceTemplateDetail;
console.log(this.serviceTemplateDetail); //Here I can see it immediately outputs the value.
this.setLoadingInitial(false);
});
} catch (error) {
console.log(error);
this.setLoadingInitial(false);
}
}
}
Child component
Here is where I am using the Store, when I use the useEffect Hook it actually populates the data, but when I run in inside onClick function it does not populate the value.
What my understanding is that Axios GET call executes as expected, also it returns the value back and assigns it to serviceTemplateDetail variable. but when I am accessing the value via getServiceTemplateDetail method it returns null for the first time, and when I click the Import Button next time it returns the old value which was returned from GET Request
import DataGrid, { Selection } from "devextreme-react/data-grid";
import Popup, { Position, ToolbarItem } from "devextreme-react/popup";
import { Column } from "devextreme-react/tree-list";
import { observer } from "mobx-react-lite";
import React, { Component, useCallback, useEffect, useState } from 'react'
import { useStore } from "../store/Store";
export default observer(function ImportServiceTemplate(props: importServiceProp) {
const [ serviceTemplateIds, setServiceTemplateIds] = useState([]);
const { serviceTemplateStore } = useStore();
const { serviceTemplateList, loadServiceTemplateList, loadServiceTemplateDetail, getServiceTemplateDetail, serviceTemplateDetail } = serviceTemplateStore;
useEffect(() => {
if (serviceTemplateList?.length === 0 || serviceTemplateList === undefined) loadServiceTemplateList();
}, [loadServiceTemplateList])
const closeButtonOption = {
icon: 'close',
text: 'Close',
onClick: ()=>{
props.onCloseImportModel();
}
};
//Added a useEffect to test..
//UseEffect returns the value but not my Import function below
useEffect(() => {
console.log("use effect");
console.log(JSON.stringify(getServiceTemplateDetail));
}, [getServiceTemplateDetail])
//Actual function that needs to work.
const importButtonOption = {
icon: 'download',
text: 'Import',
onClick: () => {
if(serviceTemplateIds){
loadServiceTemplateDetail(String(serviceTemplateIds))
.then(()=>{
console.log("Callback");
console.log(JSON.stringify(serviceTemplateDetail)); // Getting undefined as output.
props.importingServiceTemplate(getServiceTemplateDetail); //Passing the imported value to parent component
});
}
}
};
const onSelectionChanged = (e: any) => {
console.log("Processing", e.selectedRowKeys);
setServiceTemplateIds(e.selectedRowKeys);
};
return (
<>
<Popup
visible={props.isImportVisible}
dragEnabled={false}
closeOnOutsideClick={false}
showCloseButton={false}
showTitle={true}
title="Service Template"
width={800}
height={280}>
<Position
at="center"
my="center"
/>
<DataGrid
id="serviceTemplateGrid"
key="ServiceTemplateId"
keyExpr="ServiceTemplateId"
focusedRowEnabled={true}
onSelectionChanged={onSelectionChanged}
selectedRowKeys={serviceTemplateIds}
dataSource={serviceTemplateList}
showRowLines={true}
showBorders={true}>
<Selection mode="multiple" showCheckBoxesMode="onClick" />
<Column dataField="Name" caption="Name" />
<Column dataField="CustomerName" caption="Customer Name" />
<Column dataField="BaseCurrencyCode" caption="Currency" />
<Column dataField="Description" caption="Description" />
</DataGrid>
<ToolbarItem
widget="dxButton"
toolbar="bottom"
location="before"
options={closeButtonOption}
/>
<ToolbarItem
widget="dxButton"
toolbar="bottom"
location="after"
options={importButtonOption}
/>
<div>{JSON.stringify(getServiceTemplateDetail)}</div>
</Popup>
</>
)
})
interface importServiceProp{
isImportVisible: boolean;
onCloseImportModel: Function
importingServiceTemplate: any
}
It is not React or MobX problem, just a regular javascript closure.
When you create importButtonOption function it remembers all the variables around it, and serviceTemplateDetail is equals undefined at first time. So after you invoke loadServiceTemplateDetail serviceTemplateDetail is changed in the store, but inside importButtonOption function it is still an old value which was remembered when the function was created.
Hope it makes sense. Basically you just need to read about closures and how they work.
There is a little guide in React docs
What you can do for example is remove destructuring of values and dereference them as you need, like that:
loadServiceTemplateDetail(String(serviceTemplateIds))
.then(()=>{
console.log("Callback");
console.log(JSON.stringify(serviceTemplateStore .serviceTemplateDetail)); // reference it from the store to get actual value
props.importingServiceTemplate(getServiceTemplateDetail); //Passing the imported value to parent component
});
I have a component that displays search data returned from the Spotify API. However, every time I update the state the UI flickers:
Input:
<DebounceInput
debounceTimeout={300}
onChange={handleChange}
/>
Hook:
const [searchResults, setSearchResults] = useState(null)
API call w/ Apollo:
const searchSpotify = async (query) => {
const result = await props.client.query({
query: SearchTracks,
variables: {
query
}
})
const tracks = result.data.searchedTracks
setSearchResults(tracks)
}
Render:
{searchResults &&
<div className="search-results">
{searchResults.map((song) => (
<SongInfo key={song.id} {...song} />
))}
</div>
}
I noticed it only happens on the first load. For example, if I were to type the query again it shows without flickering. Is there a better way to implement this so the UI doesn't flicker?
Below are the frames that cause the flicker. What I think is happening is it takes some time for the images to load. While they are loading the items have reduced height. You should make sure SongInfo layout does not depend on whether the image has been loaded or not.
Images not loaded - items are collapsed:
Images were loaded:
I think whats happening is that you are executing a search query on every key stroke which is causing the weird behavior.
Use lodash debounce to avoid doing a search on every key stroke.
That should address the flickering. (Also, adding a loading state will help)
Sample debounce component
import React, {Component} from 'react'
import { debounce } from 'lodash'
class TableSearch extends Component {
//********************************************/
constructor(props){
super(props)
this.state = {
value: props.value
}
this.changeSearch = debounce(this.props.changeSearch, 250)
}
//********************************************/
handleChange = (e) => {
const val = e.target.value
this.setState({ value: val }, () => {
this.changeSearch(val)
})
}
//********************************************/
render() {
return (
<input
onChange = {this.handleChange}
value = {this.props.value}
/>
)
}
//********************************************/
}
In my code, I did not use constructor (). I've always seen people use the constructor in class components, but even though I'm not using it in that code, it's working perfectly. In my code, putting the state outside the constructor, is it a good idea or would it be better to use the constructor with the state set inside it? Can it give some sort of error in the future, or worsen my system's performance doing so? What is more advisable to do in this case?
import React, { Component, Fragment } from 'react'
import {Redirect} from 'react-router-dom'
import { connect } from 'react-redux'
import ActionCreator from '../redux/actionCreators'
import Button from '../elements/Button'
const statsgenre = {
'Ação': 'Action',
'Comédia': 'Comedy',
'Drama': 'Drama'
}
const statsuser = {
'Assistido' : 'Watched',
'Assistindo': 'Watching',
'Assistir': 'Watch'
}
class ScreensEditSeries extends Component{
state = {
id: '',
name: '',
status: '',
genre: '',
notes: ''
}
componentDidMount = () => {
const serie = {...this.props.match.params}
this.props.load(serie)
this.props.reset()
}
static getDerivedStateFromProps(newProps, prevState){
let serie = {}
if (prevState.name === '' || prevState.name === undefined){
if (newProps.series.serie.name !== prevState.name){
serie.name = newProps.series.serie.name
}
if (newProps.series.serie.genre !== prevState.genre){
serie.genre = newProps.series.serie.genre
}
if (newProps.series.serie.status !== prevState.status){
serie.status = newProps.series.serie.status
}
if (newProps.series.serie.notes !== prevState.notes){
serie.notes = newProps.series.serie.notes
}
return serie
}
}
saveSeries = () => {
const {name, status, genre, notes} = this.state
const id = this.props.match.params.id
const newSerie = {
id,
name,
status,
genre,
notes
}
this.props.save(newSerie)
}
handleChange = field => event => {
this.setState({[field] : event.target.value})
}
render(){
return (
<Fragment>
<div className="container">
<div>
{this.props.series.saved && <Redirect to={`/series/${this.props.match.params.genre}`}/>}
<h1 className='text-white'>Edit Série</h1>
{!this.props.series.isLoadding && <Button>
Name: <input type="text" value={this.state.name} onChange={this.handleChange('name')} className="form-control" /><br />
Status: {<span> </span>}
<select value={this.state.status} onChange={this.handleChange('status')}>
{Object.keys(statsuser)
.map( key => <option key={key}>{statsuser[key]}</option>)}
</select><br/><br/>
Genre: {<span> </span>}
<select value={this.state.genre} onChange={this.handleChange('genre')}>
{Object.keys(statsgenre)
.map(key => <option key={key}>{statsgenre[key]}</option>)}
</select><br/><br/>
Notes: <textarea type='text' value={this.state.notes} onChange={this.handleChange('notes')} className="form-control"></textarea><br />
<button className="button button2" type="button" onClick={this.saveSeries}>Save</button>
</Button>}
{this.props.series.isLoadding && <p className='text-info'>Loading...</p>}
</div>
</div>
</Fragment>
)
}
}
const mapStateToProps = state => {
return {
series: state.series
}
}
const mapDispatchToProps = dispatch => {
return {
load : serie => dispatch(ActionCreator.getSerieRequest(serie)),
save: newSerie => dispatch(ActionCreator.updateSerieRequest(newSerie)),
reset : () => dispatch(ActionCreator.seriesReset()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ScreensEditSeries)
In general, you should only use a constructor if you need logic when the class is first created, or if your setup depends on the props passed in. Since everything in your initial state is hardcoded not using a constructor is fine in this case.
There is no problem in using class components without a constructor. Usually you need it in case you have to do some work to prepare the state, process some props or other setup some instance variables as soon as the component is instantiated.
It's ok :)
Here, instead, there is a very interesting post from Dan Abramov about why, if you need to use the constructor, is needed to call super(props):
https://overreacted.io/why-do-we-write-super-props/
Not super related to the question, but asking about constructor, I thought it could be useful to you.
There's no difference. The reason you see most people doing it inside of the constructor is because doing state = {} directly on the class is new syntax that hasn't been widely adopted yet (it often still requires a Babel or similar transformation). See proposal-class-fields for more information on it. One thing to note is that if you need to access any props to initialize the state, you have to do that in the constructor.
I'm working on a Notification feature in my app (pretty much like Facebook notifications).
When I click a button in the header navigation, the dropdown opens and shows the notification list. The notification has a Link (from react-router) in it.
What I need to do is to close the dropdown whenever a Link is clicked.
Here's roughly the hierarchy I currently have:
Header > Navigation > Button > Dropdown > List > Notification > Link
Since the dropdown functionality is used more that once, I've abstracted its behavior away into a HOC that uses render prop:
export default function withDropDown(ClickableElement) {
return class ClickableDropdown extends PureComponent {
static propTypes = {
children: PropTypes.func.isRequired,
showOnInit: PropTypes.bool,
};
static defaultProps = {
showOnInit: false,
};
state = {
show: !!this.props.showOnInit,
};
domRef = createRef();
componentDidMount() {
document.addEventListener('mousedown', this.handleGlobalClick);
}
toggle = show => {
this.setState({ show });
};
handleClick = () => this.toggle(true);
handleGlobalClick = event => {
if (this.domRef.current && !this.domRef.current.contains(event.target)) {
this.toggle(false);
}
};
render() {
const { children, ...props } = this.props;
return (
<Fragment>
<ClickableElement {...props} onClick={this.handleClick} />
{this.state.show && children(this.domRef)}
</Fragment>
);
}
};
}
The HOC above encloses the Button component, so I have:
const ButtonWithDropdown = withDropdown(Button);
class NotificationsHeaderDropdown extends PureComponent {
static propTypes = {
data: PropTypes.arrayOf(notification),
load: PropTypes.func,
};
static defaultProps = {
data: [],
load: () => {},
};
componentDidMount() {
this.props.load();
}
renderDropdown = ref => (
<Dropdown ref={ref}>
{data.length > 0 && <List items={this.props.data} />}
{data.length === 0 && <EmptyList />}
</Dropdown>
);
render() {
return (
<ButtonWithDropdown count={this.props.data.length}>
{this.renderDropdown}
</ButtonWithDropdown>
);
}
}
List and Notification are both dumb functional components, so I'm not posting their code here. Dropdown is pretty much the same, with the difference it uses ref forwarding.
What I really need is to call that .toggle() method from ClickableDropdown created by the HOC to be called whenever I click on a Link on the list.
Is there any way of doing this without passing that .toggle() method down the Button > Dropdown > List > Notification > Link subtree?
I'm using redux, but I'm not sure this is the kind of thing I'd put on the store.
Or should I handle this imperatively using the DOM API, by changing the implementation of handleGlobalClick from ClickableDropdown?
Edit:
I'm trying with the imperative approach, so I've changed the handleGlobalClick method:
const DISMISS_KEY = 'dropdown';
function contains(current, element) {
if (!current) {
return false;
}
return current.contains(element);
}
function isDismisser(dismissKey, current, element) {
if (!element || !contains(current, element)) {
return false;
}
const shouldDismiss = element.dataset.dismiss === dismissKey;
return shouldDismiss || isDismisser(dismissKey, current, element.parentNode);
}
// Then...
handleGlobalClick = event => {
const containsEventTarget = contains(this.domRef.current, event.target);
const shouldDismiss = isDismisser(
DISMISS_KEY,
this.domRef.current,
event.target
);
if (!containsEventTarget || shouldDismiss) {
this.toggle(false);
}
return true;
};
Then I changed the Link to include a data-dismiss property:
<Link
to={url}
data-dismiss="dropdown"
>
...
</Link>
Now the dropdown is closed, but I'm not redirected to the provided url anymore.
I tried to defer the execution of this.toggle(false) using requestAnimationFrame and setTimeout, but it didn't work either.
Solution:
Based on the answer by #streletss bellow, I came up with the following solution:
In order to be as generic as possible, I created a shouldHideOnUpdate prop in the ClickableDropdown dropdown component, whose Hindley-Milner-ish signature is:
shouldHideOnUpdate :: Props curr, Props prev => (curr, prev) -> Boolean
Here's the componentDidUpdate implementation:
componentDidUpdate(prevProps) {
if (this.props.shouldHideOnUpdate(this.props, prevProps)) {
this.toggle(false);
}
}
This way, I didn't need to use the withRouter HOC directly in my withDropdown HOC.
So, I lifted the responsibility of defining the condition for hiding the dropdown to the caller, which is my case is the Navigation component, where I did something like this:
const container = compose(withRouter, withDropdown);
const ButtonWithDropdown = container(Button);
function routeStateHasChanged(currentProps, prevProps) {
return currentProps.location.state !== prevProps.location.state;
}
// ... then
render() {
<ButtonWithDropdown shouldHideOnUpdate={routeStateHasChanged}>
{this.renderDropdown}
</ButtonWithDropdown>
}
It seems you could simply make use of withRouter HOC and check if this.props.location.pathname has changed when componentDidUpdate:
export default function withDropDown(ClickableElement) {
class ClickableDropdown extends Component {
// ...
componentDidUpdate(prevProps) {
if (this.props.location.pathname !== prevProps.location.pathname) {
this.toggle(false);
}
}
// ...
};
return withRouter(ClickableDropdown)
}
Is there any way of doing this without passing that .toggle() method down the Button > Dropdown > List > Notification > Link subtree?
In the question, you mention that you are using redux.So I assume that you store showOnInit in redux.We don't usually store a function in redux.In toggle function,I think you should dispatch an CHANGE_SHOW action to change the showOnInit in redux, then pass the show data not the function to the children component.Then after reducer dispatch,the react will change “show” automatically.
switch (action.type) {
case CHANGE_SHOW:
return Object.assign({}, state, {
showOnInit: action.text
})
...
default:
return state
}
Link element and data pass
Use the property in Link-to,not data-...Like this:
<Link
to={{
pathname: url,
state:{dismiss:"dropdown"}
}}
/>
And the state property will be found in this.props.location.
give context a little try(not recommend)
It may lead your project to instable and some other problems.(https://reactjs.org/docs/context.html#classcontexttype)
First,define context
const MyContext = React.createContext(defaultValue);
Second,define pass value
<MyContext.Provider value={this.toggle}>
Then,get the value in the nested component
<div value={this.context} />
I have a React component with a prop 'total' that changes every time the component is updated:
function MyView(props) {
const total = props.data.loading ? 0 : props.data.total;
return (
<p> total </p>
);
}
The first time the component mounts the total is say 10. Every time the component is updated because of a prop change the total goes up.
Is there a way I can display the original total (in this example 10)?
I have tried setting it in this.total inside componentDidMount, but props.data.total is not yet available when componentDidMount is called. Same with the constructor. The total only becomes available when props.data.loading is false.
In order to get access to lifecycle features, you must move from function, stateless component, to a class component.
in the below example, InitialTotal is initialized in the construstor lifecycle method and it never changes.
currentTotal, is incremented each time the render function is called - when the component is re-rendered (because of props change or state changes)
it should look something like that:
class MyView extends React.Component {
constructor(props) {
super(props)
this.initialTotal = 10;
this.currentTotal = 10;
}
render() {
this.currentTotal+=1;
return (
<p>InitialToal: {this.initialTotal}</p>
<p>Current Total: {this.currentTotal}</p>
);
}
}
You could create a stateful component and store the initial total in the component state.
Example
class MyView extends React.Component {
state = {
initialTotal: this.props.total
};
render() {
const { total } = this.props;
const { initialTotal } = this.state;
return (
<div>
<p> Total: {total} </p>
<p> Initial total: {initialTotal} </p>
</div>
);
}
}
class App extends React.Component {
state = {
total: 10
};
componentDidMount() {
this.interval = setInterval(() => {
this.setState(({ total }) => {
return { total: total + 1 };
});
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <MyView total={this.state.total} />;
}
}
If I understand your requirements correctly...
function MyView(props) {
// if you only need to set the value once on load just use useState.
// the const total will be the value you pass in to useState.
const [total, setTotal] = useState(props.data.loading ? 0 : props.data.total)
// if its possible that the value is not available on initial load and
// you want to set it only once, when it becomes available, you can use
// useEffect with useState
useEffect(() => {
// some condition to know if data is ready to set
if (!props.data.loading) {
setTotal(props.data.total)
}
}, [props.data.total, setTotal, props.data.loading]
// this array allows you to limit useEffect to only be called when
// one of these values change. ( when total changes in this case,
// as the const function setTotal will not change
// ( but react will fuss if its used and not in the list ).
return (
<p> {total} </p>
);
}
I have the same need. With a functional component, I need to store the inital snapshot of states, let user play with different state values and see their results immediately, eventually, they can just cancel and go back to the initial states. Apply the same structure to your problem, this is how it looks:
import React from 'react';
import { useEffect, useState } from "react";
const TestView = (props: { data: any }) => {
// setting default will help type issues if TS is used
const [initialTotal, setInitialTotal] = useState(props.data.total)
useEffect(() => {
// some condition to know if data is ready to set
setInitialTotal(props.data.total);
// Critical: use empty array to ensure this useEffect is called only once.
}, [])
return (
<div>
<p> { initialTotal } </p>
<p> { props.data.total } </p>
</div>
);
}
export default TestView
You can use getDerivedStateFromProps life cycle method.
static getDerivedStateFromProps(props, state){
if(props.data.total && (props.data.total==10)){
return {
total : props.total // show total only when its 10
}
}else{
return null; // does not update state
}
}