I’m very new learning React, however, I want to be able to scale a class-project using localStorage, saving the text into a button and when I refresh the browser that keep and, delete it when I want, since said button already is configured with a couple of actions, but I couldn’t.
Could you help me resolve this problem, please.
`import ‘../Style-sheet/FormTask.css’;
import { v4 as uuidv4 } from ‘uuid’;
import { useLocalStorage } from ‘./localStorage’;
function FormTask(props) {
const [input, setInput] = useLocalStorage('input', '')
const handleChange = e => {
setInput(e.target.value);
};
const handleShipping = e => {
e.preventDefault();
const newTask = {
id: uuidv4(),
text: input,
fulfilled: false,
};
props.onSubmit(newTask);
};
return (
<form
className='form-task'
onSubmit={handleShipping}>
<input
className='input-task'
type='text'
placeholder='Write a task'
name='text'
onChange={handleChange}
/>
<button className='button-task'
onClick={() => ('')}>
Add Task
</button>
</form>
)
};
export default FormTask;`
`import { useState } from ‘react’;
export function useLocalStorage (key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
return initialValue
};
});
const setValue = value => {
try {
setStoredValue(value)
window.localStorage.setItem(key, JSON.stringify(value))
} catch (error) {
console.error(error)
};
};
return [storedValue, setValue];
};
`
I tried to reproduce your problem inside this sandbox:
https://codesandbox.io/p/sandbox/lucid-brook-mqsch2?file=%2Fsrc%2Findex.js&from-embed=
Your problem is not using the value property inside the input:
<form
className='form-task'
onSubmit={handleShipping}>
<input
className='input-task'
type='text'
placeholder='Write a task'
name='text'
onChange={handleChange}
// add
value={input}
/>
<button className='button-task'
onClick={() => ('')}>
Add Task
</button>
</form>
Now your input field should always have the value from the local storage, even on page refresh!
1