I made a submit form in alpine.js that dynamically adds data. However, if I click on the refresh button, the data gets wiped out. How can I have it so that every time I refresh the browser after adding names, the data stays the same? I thought of using local storage, but had difficulty with figuring out how to implement it.
Here is my html:
<div class="container py-4" x-data="addRemove()">
<hr>
<form x-on:submit.stop.prevent="addRemoveSubmit">
<div class="row">
<div class="col">
<div class="form-group">
<label for="first">First</label>
<input type="text" class="form-control" id="text" aria-describedby="text" x-model="newFirst">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="last">Last</label>
<input type="text" class="form-control" id="last" aria-describedby="last" x-model="newLast">
</div>
</div>
<div class="col-2 d-flex align-items-end">
<div class="form-group col px-0">
<button type="submit" class="btn btn-primary btn-block">Add</button>
</div>
</div>
</div>
</form>
<table class="table table-bordered mt-2 mb-4">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<template x-for="(person, index) in Object.values(persons)" :key="index">
<tr>
<td x-text="person.first"></td>
<td x-text="person.last"></td>
<td><button x-on:click="persons = persons.filter(p => p.id !== person.id)" class="btn btn-danger btn-block">Remove</button></td>
</tr>
</template>
</tbody>
</table>
</div>
Here is my Javascript:
function randId() {
return (Math.random() * 100).toFixed(0);
}
function addRemove() {
return {
newFirst: '',
newLast: '',
persons: '',
addRemoveSubmit() {
this.persons = [].concat({
id: randId(),
first: this.newFirst,
last: this.newLast
}, this.persons); this.newFirst = '', this.newLast = '';
}
}
}