I am using the following in my react form (formik library) to display a text field.
How can I store the value of the text field in sessionstorage as soon as user finishes typing something in the text field? had it been a select, I would have added Onclick
function to store the selection into session storage.
import {Button, InputLabel,Menu,MenuItem, Select, TextField, TextareaAutosize} from '@material-ui/core'
import {styled} from "@material-ui/core/styles";
const StyledTextField = styled(TextField)( {
width: '50%',
})
const CustomTextField = ({
placeholder,
...props
}) => {
const [field, meta] = useField(props);
const errorText = meta.error && meta.touched ? meta.error : "";
return (
<div>
<InputLabel>{placeholder}</InputLabel>
<StyledTextField
{...field}
helperText={errorText}
error={!!errorText}
/>
</div>
);
};
<CustomTextField name = "textDescription" type ="text" placeholder="Text Description"/>
The reason I want t ostore it in storage is because I am using file upload (advanced) version and as soon as user clicks on upload
button, I want to grab the description from storage and use it in the api call.
After typing something, I tried using the following:
console.log("Printing Document By getElementbyID value");
console.log(document.getElementById('textDescription').value);
But it keeps on printing Uncaught TypeError: document.getElementById(...) is null
Troubleshooting results based on Bassam Rubaye's answer:
Added an event like this:
<StyledTextField
{...field}
helperText={errorText}
error={!!errorText}
onChange={handleChange}
/>
And tried the following:
const handleChange = e => {
console.log("Value of Description");
console.log(e.target.value);
}
It is printing like the following in console.log
:
Value of Description
t
Value of Description
te
Value of Description
tes
Value of Description
test
Is it going to store test
in the session storage?
I am not exactly sure about your use case, but You can add a handler for "onChange" event on the StyledTextField, and inside that handler, you can add the value of that component to the sessionStorage
handleChange(e) {
/** you will need to throttle the call here as well
to avoid calling setItem with each change but only calling it after for example 300MS to make sure the user has completed typing
*/
sessionStorage.setItem("yourKey", e.target.value);
}