import React, { useState, useRef, useReducer } from "react";
import "./App.css";
function reducer(state,action){
const {past,present,future} = state
switch(action.type){
case 'ADD' : return {
past : [...past,present],
present : [...present,{id : Math.random(),name : action.payload}],
future : [],
canUndo : true,
canRedo : false,
}
case "UNDO" : if(!state.canUndo) return state;
return {
present :past[past.length - 1],
past : past.slice(0,-1),
future : [present,...future],
canUndo : past.length > 1,
canRede : true
}
case 'REDO' : return {
}
default: return state;
}
}
function App(){
const input = useRef();
const initialState = {
present : [],
past : [],
future : [],
canUndo : false,
canRedo : false,
}
const[items,dispatch] = useReducer(reducer,initialState);
const addItem = (e) => {
e.preventDefault();
dispatch({type : 'ADD', payload : input.current.value})
input.current.value = '';
}
return(
<div>
<h1>Shopping list</h1>
<form className='add-product' onSubmit={addItem}>
<label htmlFOR='product'>product</label>
<input ref={input} type='text' id='product'/>
<button type='submit'>Add</button>
</form>
<div className='actions'>
<button onClick={() => dispatch({type : 'UNDO'})}>Undo</button>
<button onClick={() => dispatch({type : 'REDO'})}>Redo</button>
</div><ul>
{items.present.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
</div>
)
}
export default App;
Hello Everyone, i am having hard time understanding this concept
present : past[past.length - 1]
So after adding a value, This should return a single value when I click on Undo button, but it is returning a full array except the last one, if anyone explains this concept I will be very thankful, why it is behaving like slice method