How to get previous variable value on React Hooks

Viewed 196

I have a variable that is already setup from the API result, the value is an array:

tier_items = [{id:1, name:'coffee'}, {id:2, name:'tea'}, {id:2, name:'juice'}]

this tier_items value is always updated with this condition

useEffect(()=>{console.log('tier_items')}, [tier_items])

value after updated : tier_items = [{id:1, name:'coffee'}]

I need to get both the previous & current value of updated tier_items

const [current, setCurrent] = useState(tier_items) 
const [previous, setPrevious] = ???

this is the expected result

current = [{id:1, name:'coffee'}]

previous = [{id:1, name:'coffee'}, {id:2, name:'tea'}, {id:2, name:'juice'}]

also the next upcoming value onwards

1 Answers

You must update previous when updating current, for example :

setCurrent((current) => {
    setPrevious((currentPrevious) => return [...current, ...currentPrevious])
    return [{id:1, name:'coffee'}];
}

That should do what you want :)

Related