I\'m trying to make shopping cart front end with localstorage, as there are some modal windows and I need to pass cart items info there. Every time you click add to cart it
You're overwriting the other objects every time, you need to use an array to hold them all:
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'product-name': itemContainer.find('h2.product-name a').text(),
'product-image': itemContainer.find('div.product-image img').attr('src'),
'product-price': itemContainer.find('span.product-price').text()
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
http://jsfiddle.net/JLBaA/1/
You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in localStorage.
it's not directly related to local storage but nowdays, it's a good practice to use React/Angular. here is a example:
var TodoItem = React.createClass({
done: function() {
this.props.done(this.props.todo);
},
render: function() {
return <li onClick={this.done}>{this.props.todo}</li>
}
});
var TodoList = React.createClass({
getInitialState: function() {
return {
todos: this.props.todos
};
},
add: function() {
var todos = this.props.todos;
todos.push(React.findDOMNode(this.refs.myInput).value);
React.findDOMNode(this.refs.myInput).value = "";
localStorage.setItem('todos', JSON.stringify(todos));
this.setState({ todos: todos });
},
done: function(todo) {
var todos = this.props.todos;
todos.splice(todos.indexOf(todo), 1);
localStorage.setItem('todos', JSON.stringify(todos));
this.setState({ todos: todos });
},
render: function() {
return (
<div>
<h1>Todos: {this.props.todos.length}</h1>
<ul>
{
this.state.todos.map(function(todo) {
return <TodoItem todo={todo} done={this.done} />
}.bind(this))
}
</ul>
<input type="text" ref="myInput" />
<button onClick={this.add}>Add</button>
</div>
);
}
});
var todos = JSON.parse(localStorage.getItem('todos')) || [];
React.render(
<TodoList todos={todos} />,
document.getElementById('container')
);
from here