Upon componentWillUnmount I want to send an array inside a useState to a postRequest function.
My useState array:
const [array, setArray] = useState([]);
My componentWillUnmount function:
useEffect(() => {
return () => {
console.log(array); // logs "[]"
// TODO: Send to a post request to BE
}
}, [])
I do also have a "normal" useEffect that listens on my useState array. When I add three elements inside it, the console logs shows there are three elemetns inside it
useEffect(() => {
console.log('array: ', array); // logs "(3) [{…}, {…}, {…}]"
}, [array]);
How come the array is empty in my componentWillUnmount function?
Edit: Adding array to the dependecy of the useEffect will make the function execute every time that array is updated, which is not what is desired. The function should only execute upon unmount with the values of the array
CodePudding user response:
It's because the value of the variable did not changed inside hook because it initiated on componentDidMount
and did not received an update because the second parameter is empty.
Since you only want to trigger it once if the component unmounts and not every time the value changes:
you can use useRef
to "preserve" the value without rerendering the component.
const ref = useRef();
useEffect(() => {
ref.current = array;
}, [array]);
useEffect(() => {
return function cleanup() {
console.log(ref.current); // here is your array
};
}, []);
CodePudding user response:
When passing an empty dependency array as second argument to useEffect
, the code inside the useEffect
callback will only be run on mount. At this moment, array is still empty.
Does it work when you also add the array to the dependency array of the first useEffect like this?
useEffect(() => {
return () => {
console.log(array); // logs "[]"
// TODO: Send to a post request to BE
}
}, [array])
BTW, I think you can also combine the two like this:
useEffect(() => {
console.log('array: ', array); // logs "(3) [{…}, {…}, {…}]"
return () => {
console.log(array); // logs "[]"
// TODO: Send to a post request to BE
}
}, [array])