Сначала вы должны получить то, что находится в вашем хранилище, прежде чем обновлять его.
Объявите key
при запуске, затем объявите localStorageArray
, указав текущее значение хранилища:
handleSubmit = (e,props) => {
let key = 'Item 1';
// Retrieves your storage, or initializes it with an empty array if nothing is found.
let localStorageArray = JSON.parse(localStorage.getItem(key) || '[]');
let myObj = {name : this.props.UserName,
Email : this.props.email,
Password : this.props.password,
Phone : this.props.phone};
e.preventDefault();
// Pushes your new object.
localStorageArray.push(myObj);
// Updates your storage.
localStorage.setItem(key, JSON.stringify(localStorageArray));
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
change={...values};
this.props.changeState(change);
}
});
};
Ниже приведен рабочий пример:
// As the document is sandboxed, the following is to simulate the "localStorage".
const CustomStorage = { data: {} };
CustomStorage.getItem = (key) => CustomStorage.data[key];
CustomStorage.setItem = (key, value) => (CustomStorage.data[key] = value);
// ----------
const eAddBtn = document.querySelector('#btn-add'),
eLogBtn = document.querySelector('#btn-log');
// logs the storage's data.
eLogBtn.addEventListener('click', () => console.log(JSON.parse(CustomStorage.getItem('_key') || '[]')));
// Adds an entry into the storage.
eAddBtn.addEventListener('click', () => {
const eInputs = document.querySelectorAll('input'),
storageKey = '_key',
storageItem = JSON.parse(CustomStorage.getItem(storageKey) || '[]'),
obj = {};
Array.from(eInputs).forEach(eInput => obj[eInput.id] = eInput.value);
storageItem.push(obj);
CustomStorage.setItem(storageKey, JSON.stringify(storageItem));
});
<label for="name">
<input id="name" type="text" placeholder="name">
</label>
<label for="age">
<input id="age" type="number" min="0" placeholder="age">
</label>
<button id="btn-add">Add to storage</button>
<button id="btn-log">Log the storage</button>