I want to store the previous value in a variable and use it in a function. Let's say if the current value is 9, the previous value is supposed to be 8 (like one less). The problem is that console.log(prevServings)
returns undefined on the first render and shows the previous value on the second render but the difference between current and previous values are 2 instead of 1. My understanding is that the current value is not available on the first render so the previous value is undefined but I don't know how to fix it. Any help would be appreciated. Thanks in advance.
const Child = ({originalData}) =>{
//clone original data object with useState
const [copyData, setCopyDta] = useState({});
//clone the copied data
let duplicate = {...copyRecipe};
//store previous servings value into a variable
const usePrevious = (servings) => {
const ref = useRef();
useEffect(() => {
ref.current = servings;
}, [servings]);
return ref.current;
};
const prevServings = usePrevious(duplicate.servings);
//increase the number of servings on click
const incrementHandle = () => {
duplicate.servings = `${parseInt(duplicate.servings) + 1}`;
//this return undefined on the first render
console.log(prevServings);
setCopyRecipe(duplicate);
}
return(
<p>{copyData.servings}</p>
<Increment onClick={incrementHandle}/>
)
}