I am working with react.js, and i have the following code.
function App() {
let Submitable;
const [values, setValues] = useState([])
//...
onTicket.save = () => {
console.log(Submitable) // logs undefiened
if (Submitable) {
return true
} else {
return `Please fill out the following fields before submitting:${values.map(el => ` ${el.name}`)}`
}
})
useEffect(() => {
if (values.length === 0) {
Submitable = true
//enableSave
} else {
Submitable = false
//disableSave
}
}, [values])
return (
<>
///jsx code block
</>
);
}
export default App;
I would think that in the useEffect function setting Submitable to either true or false, the value would carry to other functions but when called, Submitable logs undefined. And if I try to pass Submitable as a parameter it also logs undefined.
Assignments from inside an useEffect
will be lost upon each render. To preserve the value over time store it in a useRef
hook and keep the mutable value inside current
property
const Component = () =>{
const submitable = useRef()
useEffect(() =>{
submitable.current = 'foo'
},[])
console.log(submitable.current) // 'foo'
}