Let's say I have a class designed to take care of complex operations called UtilityClass and is set up as:
export default class UtilityClass {
constructor(name, setName) {
this.name = name
this.setName = setName
}
changeName(newName) {
this.setName(newName)
}
printName() {
console.log(this.name)
}
}
I want to initialise this class from my functional component and call its functions on button clicks:
import UtilityClass from './UtilityClass'
export function App(props) {
const utilityClass = useRef()
const [name, setName] = useState()
useEffect(() => {
utilityClass.current = new UtilityClass(name, setName)
}, [])
function setViaClass(newName) {
utilityClass.current.changeName(newName)
}
function printViaClass() {
utilityClass.current.printName()
}
return (
<>
<button onClick={() => setViaClass('Class')}>Set via class</button>
<button onClick={printViaClass}>Print via class</button>
</>
);
}
If I call UtilityClass.setName(), the value of the state variable will change, but printing this.name from within UtilityClass will display undefined.
Why is this.name not synced with what the state value really is?
The reason I have UtilityClass instead of having the logic directly in my functional component is that the logic should be called across multiple functional components, and I want to split my code into smaller readable bits.