How to bind context to React Functional Component - reactjs

I have a function that I call from a child component callback. I'm trying to access some state variable but variables are undefined. I think the issue is when the child component callback the function context it not bind to the parent component. How to do this.
It is sure that myVariable is set before myFunciton is called.
const MyParentView = props => {
const[myVariable, setMyVariable] = useState(undefined)
const onTextFieldChange = val => {
setMyVariable(val)
}
const myFunction = () => {
// myVariable is set to some value by this time
console.log(myVariable)
// But it logs undefined
}
return (
<Input onChange={e => onTextFieldChange(e.target.value)}
<MyChildComponent getData={()=>myFunction()}/>
)
}
Following is the child component ( The actual one )
// #flow
import React, { useEffect, useRef } from "react"
import { get } from "lodash"
type Props = {
children: any,
getData?: Function,
threshold?: number
}
const InfiniteScroll = ({ children, getData, threshold = 0.9 }: Props) => {
const listRef = useRef()
useEffect(() => {
window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll)
}, [])
useEffect(() => {
if (listRef.current) {
const bottom = listRef.current.getBoundingClientRect().bottom
const height =
window.innerHeight || get(document, "documentElement.clientHeight")
if (bottom <= height) {
getData && getData()
}
}
})
const handleScroll = () => {
const winScroll =
get(document, "body.scrollTop") ||
get(document, "documentElement.scrollTop")
const height =
get(document, "documentElement.scrollHeight") -
get(document, "documentElement.clientHeight")
const scrolled = winScroll / height
if (scrolled >= threshold) {
getData && getData()
}
}
return <div ref={listRef}>{children}</div>
}
export default InfiniteScroll

Try returning a closure in your myFunction like this:
const myFunction = () => {
return function() {
// myVariable is set to some value by this time
console.log(myVariable)
// But it logs undefined
}
}

Related

In my code snippet why useEffect shows useState variable as one valuel, but when I use this variable in a logic it's another value?

I'm very confused, I have parent and a child component. What It's doing is if condition is matched in a child component, then it add's child component to array. When there is transitionis in child component it calls a deleteMe function in parent component. Real problem what I deal with is a line deleteMe function, line where I have console.log. This line ALWAYS prints me that there is [{...}] one element in array. While useEffect hook shows me that updating an array happens just fine.
Why when I call same variable it gives me different results from deleteMe func and usEffect ?
import { FC, useRef, useState, ReactElement, useEffect} from "react"
import "./marquee.scss"
import MarqueeItem from "./Item/Item"
const Marquee: FC <{text: string}> = ({ text }) => {
let cnt = useRef<number>(0)
const [marquees, setMarquees] = useState< ReactElement[]>(
[<MarqueeItem
key={cnt.current}
launchNext={() => launchNext()}
deleteMe={() => deleteMe()}
text={text}/>]
)
const deleteMe = () => {
console.log(marquees, "inside deleteMe")
if(marquees.length > 5) { // Here I have an issue. Cause "marquees" is ALWAYS 1 element !
console.log("More then 5")
}
}
const launchNext = () => {
cnt.current = cnt.current + 1;
setMarquees(oldArr => [...oldArr, <MarqueeItem key={cnt.current} deleteMe={() => deleteMe()} launchNext={() => launchNext()} text={text}/>])
}
useEffect(() => {
console.log(marquees, "useEffect")
})
return <div className="marquee">
{ marquees }
</div>
}
export default Marquee
Child component :
const MarqueeItem: FC<IProps> = ({text, launchNext, deleteMe }) => {
let observed = useRef<HTMLParagraphElement>(null)
const isReady = <T extends number>(currLeft: T, header_width: T , p_width: T): boolean => {
return currLeft < 0 && (p_width + currLeft) < header_width ? true : false
}
useEffect(() => {
const marquee = observed.current!
const transitionendListener = () => deleteMe()
marquee.addEventListener("transitionend", transitionendListener) // calling deleteMe when transition is over
const parantNode = marquee.parentNode as Element
const header_width = parseInt(getComputedStyle(parantNode).width)
const p_width = parseInt(getComputedStyle(marquee).width)
marquee.style.left = -p_width + "px"
const intervalRead = setInterval(() => {
let currLeft = parseInt(getComputedStyle(marquee).left)
if(isReady(currLeft, header_width, p_width)) {
launchNext() // adding a new element to array in parent when it's good condition to add
clearInterval(intervalRead)
}
}, 400)
return () => {
marquee.removeEventListener("transitionend", transitionendListener)
}
}, [observed, launchNext, deleteMe])
return <p ref={observed} className="marquee__text">{text}</p>
}
export default MarqueeItem

How can I reference the originally created hook in React?

I have the following usage of my hook, but it doesn't use the new timerDuration when I update inside my input:
const [secondsBetweenRepsSetting, setSecondsBetweenRepsSetting] = useState(DEFAULT_SECONDS_BETWEEN_REPS)
const {secondsLeft, isRunning, start, stop} = useTimer({
duration: secondsBetweenRepsSetting,
onExpire: () => sayRandomExerciseName(),
onTick: () => handleTick(),
});
const onTimeBetweenRepsChange = (event: any) => {
const secondsBetweenRepsSettingString = event.target.value;
const secondsBetweenRepsSettingInt = parseInt(secondsBetweenRepsSettingString)
setSecondsBetweenRepsSetting(secondsBetweenRepsSettingInt)
}
return <React.Fragment>
<input type="number" name="secondsBetweenRepsSetting" value={secondsBetweenRepsSetting} onChange={onTimeBetweenRepsChange}/>
</React.Fragment>
And here is the implementation of the useTimer hook, which I'm not sure why it's not getting my duration update?
import { useState } from 'react';
import Validate from "../utils/Validate";
import useInterval from "./useInterval";
export default function useTimer({ duration: timerDuration, onExpire, onTick}) {
const [duration] = useState(timerDuration)
const [secondsLeft, setSecondsLeft] = useState(timerDuration)
const [isRunning, setIsRunning] = useState(false)
function start() {
setIsRunning(true)
}
function stop() {
setIsRunning(false)
}
function handleExpire() {
Validate.onExpire(onExpire) && onExpire();
}
useInterval(() => {
const secondsMinusOne = secondsLeft - 1;
setSecondsLeft(secondsMinusOne)
if(secondsMinusOne <= 0) {
setSecondsLeft(duration) // Reset timer automatically
handleExpire()
} else {
Validate.onTick(onTick) && onTick();
}
}, isRunning ? 1000 : null)
return {secondsLeft, isRunning, start, stop, }
}
Remove the line:
const [duration] = useState(timerDuration);
You are already getting duration from timerDuration, just use that.

How do I clear out an Image.getSize request when unmounting a React Native component?

I have a React Native component that makes an Image.getSize request for each image in the component. Then within the callback of the Image.getSize requests, I set some state for my component. That all works fine, but the problem is that it's possible for a user to transition away from the screen the component is used on before one or more Image.getSize requests respond, which then causes the "no-op memory leak" error to pop up because I'm trying to change state after the component has been unmounted.
So my question is: How can I stop the Image.getSize request from trying to modify state after the component is unmounted? Here's a simplified version of my component code. Thank you.
const imgWidth = 300; // Not actually static in the component, but doesn't matter.
const SomeComponent = (props) => {
const [arr, setArr] = useState(props.someData);
const setImgDimens = (arr) => {
arr.forEach((arrItem, i) => {
if (arrItem.imgPath) {
const uri = `/path/to/${arrItem.imgPath}`;
Image.getSize(uri, (width, height) => {
setArr((currArr) => {
const newWidth = imgWidth;
const ratio = newWidth / width;
const newHeight = ratio * height;
currArr = currArr.map((arrItem, idx) => {
if (idx === i) {
arrItem.width = newWidth;
arrItem.height = newHeight;
}
return arrItem;
});
return currArr;
});
});
}
});
};
useEffect(() => {
setImgDimens(arr);
return () => {
// Do I need to do something here?!
};
}, []);
return (
<FlatList
data={arr}
keyExtractor={(arrItem) => arrItem.id.toString()}
renderItem={({ item }) => {
return (
<View>
{ item.imgPath ?
<Image
source={{ uri: `/path/to/${arrItem.imgPath}` }}
/>
:
null
}
</View>
);
}}
/>
);
};
export default SomeComponent;
I had to implement something similar, I start by initialising a variable called isMounted.
It sets to true when the component mounts and false to when the component will unmount.
Before calling setImgDimens there's a check to see if the component is mounted. If not, it won't call the function and thus will not update state.
const SomeComponent = (props) => {
const isMounted = React.createRef(null);
useEffect(() => {
// Component has mounted
isMounted.current = true;
if(isMounted.current) {
setImgDimens(arr);
}
return () => {
// Component will unmount
isMounted.current = false;
}
}, []);
}
Edit: This is the answer that worked for me, but for what it's worth, I had to move the isMounted variable to outside the SomeComponent function for it to work. Also, you can just use a regular variable instead of createRef to create a reference, etc.
Basically, the following worked for me:
let isMounted;
const SomeComponent = (props) => {
const setImgDimens = (arr) => {
arr.forEach((arrItem, i) => {
if (arrItem.imgPath) {
const uri = `/path/to/${arrItem.imgPath}`;
Image.getSize(uri, (width, height) => {
if (isMounted) { // Added this check.
setArr((currArr) => {
const newWidth = imgWidth;
const ratio = newWidth / width;
const newHeight = ratio * height;
currArr = currArr.map((arrItem, idx) => {
if (idx === i) {
arrItem.width = newWidth;
arrItem.height = newHeight;
}
return arrItem;
});
return currArr;
});
}
});
}
});
};
useEffect(() => {
isMounted = true;
setImgDimens(arr);
return () => {
isMounted = false;
}
}, []);
};

useEffect triggers function several times with proper dependencies

i've got Tabs component, it has children Tab components. Upon mount it calculates meta data of Tabs and selected Tab. And then sets styles for tab indicator. For some reason function updateIndicatorState triggers several times in useEffect hook every time active tab changes, and it should trigger only once. Can somebody explain me what I'm doing wrong here? If I remove from deps of 2nd useEffect hook function itself and add a value prop as dep. It triggers correctly only once. But as far as I've read docs of react - I should not cheat useEffect dependency array and there are much better solutions to avoid that.
import React, { useRef, useEffect, useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { defProperty } from 'helpers';
const Tabs = ({ children, value, orientation, onChange }) => {
console.log(value);
const indicatorRef = useRef(null);
const tabsRef = useRef(null);
const childrenWrapperRef = useRef(null);
const valueToIndex = new Map();
const vertical = orientation === 'vertical';
const start = vertical ? 'top' : 'left';
const size = vertical ? 'height' : 'width';
const [mounted, setMounted] = useState(false);
const [indicatorStyle, setIndicatorStyle] = useState({});
const [transition, setTransition] = useState('none');
const getTabsMeta = useCallback(() => {
console.log('getTabsMeta');
const tabsNode = tabsRef.current;
let tabsMeta;
if (tabsNode) {
const rect = tabsNode.getBoundingClientRect();
tabsMeta = {
clientWidth: tabsNode.clientWidth,
scrollLeft: tabsNode.scrollLeft,
scrollTop: tabsNode.scrollTop,
scrollWidth: tabsNode.scrollWidth,
top: rect.top,
bottom: rect.bottom,
left: rect.left,
right: rect.right,
};
}
let tabMeta;
if (tabsNode && value !== false) {
const wrapperChildren = childrenWrapperRef.current.children;
if (wrapperChildren.length > 0) {
const tab = wrapperChildren[valueToIndex.get(value)];
tabMeta = tab ? tab.getBoundingClientRect() : null;
}
}
return {
tabsMeta,
tabMeta,
};
}, [value, valueToIndex]);
const updateIndicatorState = useCallback(() => {
console.log('updateIndicatorState');
let _newIndicatorStyle;
const { tabsMeta, tabMeta } = getTabsMeta();
let startValue;
if (tabMeta && tabsMeta) {
if (vertical) {
startValue = tabMeta.top - tabsMeta.top + tabsMeta.scrollTop;
} else {
startValue = tabMeta.left - tabsMeta.left;
}
}
const newIndicatorStyle =
((_newIndicatorStyle = {}),
defProperty(_newIndicatorStyle, start, startValue),
defProperty(_newIndicatorStyle, size, tabMeta ? tabMeta[size] : 0),
_newIndicatorStyle);
if (isNaN(indicatorStyle[start]) || isNaN(indicatorStyle[size])) {
setIndicatorStyle(newIndicatorStyle);
} else {
const dStart = Math.abs(indicatorStyle[start] - newIndicatorStyle[start]);
const dSize = Math.abs(indicatorStyle[size] - newIndicatorStyle[size]);
if (dStart >= 1 || dSize >= 1) {
setIndicatorStyle(newIndicatorStyle);
if (transition === 'none') {
setTransition(`${[start]} 0.3s ease-in-out`);
}
}
}
}, [getTabsMeta, indicatorStyle, size, start, transition, vertical]);
useEffect(() => {
const timeout = setTimeout(() => {
setMounted(true);
}, 350);
return () => {
clearTimeout(timeout);
};
}, []);
useEffect(() => {
if (mounted) {
console.log('1st call mounted');
updateIndicatorState();
}
}, [mounted, updateIndicatorState]);
let childIndex = 0;
const childrenItems = React.Children.map(children, child => {
const childValue = child.props.value === undefined ? childIndex : child.props.value;
valueToIndex.set(childValue, childIndex);
const selected = childValue === value;
childIndex += 1;
return React.cloneElement(child, {
selected,
indicator: selected && !mounted,
value: childValue,
onChange,
});
});
const styles = {
[size]: `${indicatorStyle[size]}px`,
[start]: `${indicatorStyle[start]}px`,
transition,
};
console.log(styles);
return (
<>
{value !== 2 ? (
<div className={`tabs tabs--${orientation}`} ref={tabsRef}>
<span className="tab__indicator-wrapper">
<span className="tab__indicator" ref={indicatorRef} style={styles} />
</span>
<div className="tabs__wrapper" ref={childrenWrapperRef}>
{childrenItems}
</div>
</div>
) : null}
</>
);
};
Tabs.defaultProps = {
orientation: 'horizontal',
};
Tabs.propTypes = {
children: PropTypes.node.isRequired,
value: PropTypes.number.isRequired,
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
onChange: PropTypes.func.isRequired,
};
export default Tabs;
useEffect(() => {
if (mounted) {
console.log('1st call mounted');
updateIndicatorState();
}
}, [mounted, updateIndicatorState]);
This effect will trigger whenever the value of mounted or updateIndicatorState changes.
const updateIndicatorState = useCallback(() => {
...
}, [getTabsMeta, indicatorStyle, size, start, transition, vertical]);
The value of updateIndicatorState will change if any of the values in its dep array change, namely getTabsMeta.
const getTabsMeta = useCallback(() => {
...
}, [value, valueToIndex]);
The value of getTabsMeta will change whenever value or valueToIndex changes. From what I'm gathering from your code, value is the value of the selected tab, and valueToIndex is a Map that is re-defined on every single render of this component. So I would expect the value of getTabsMeta to be redefined on every render as well, which will result in the useEffect containing updateIndicatorState to run on every render.

How to use State Variable (useState) in an EventHandler

I have an React Functional Component which recieves a prop with a variable from useState(). This works fine but if I use it in an EventListener it does not get updated. I tried the following but still it does not work.
Maybe someone can explain why.
Thanks
I would expect x to be the updated number but it always has the value of the initial setup of the EventHandler.
import React, { useState, useEffect } from "react";
import ReactDom from "react-dom";
const App = () => {
const [num, setNum] = useState(50);
return (
<div>
<button onClick={() => setNum(prev => prev + 1)}>Test</button>
<div>{num}</div>
<Child num={num} />
</div>
);
};
const Child = ({ num }) => {
let x = 0;
const md = () => {
console.log(num, x);
};
useEffect(() => {
x = num;
}, [num]);
useEffect(() => {
document.getElementById("box").addEventListener("mousedown", md);
return () => {
document.removeEventListener("mousedown", md);
};
}, []);
return <div id="box">click {num}</div>;
};
ReactDom.render(<App />, document.getElementById("app"));
Each render of your Child will get a new x, a new props object, etc. However you are binding your event listener only once and so capturing only the initial props.num value.
Two ways to fix:
Rebind event listener when num changes, by passing num as a dependency to your effect to bind the event listener:
const Child = ({ num }) => {
useEffect(() => {
// no need to define this in main function since it is only
// used inside this effect
const md = () => { console.log(num); };
document.getElementById("box").addEventListener("mousedown", md);
return () => {
document.removeEventListener("mousedown", md);
};
}, [num]);
return <div id="box">click {num}</div>;
};
Or use a ref to hold the value of num and bind your event listener to the ref. This gives you a level of indirection to handle the change:
const Child = ({ num }) => {
const numRef = useRef(); // will be same object each render
numRef.current = num; // assign new num value each render
useEffect(() => {
// no need to define this in main function since it is only
// used inside this effect
// binds to same ref object, and reaches in to get current num value
const md = () => { console.log(numRef.current); };
document.getElementById("box").addEventListener("mousedown", md);
return () => {
document.removeEventListener("mousedown", md);
};
}, []);
return <div id="box">click {num}</div>;
};

Resources