D
D
DeniSidorenko2020-12-22 07:19:37
redux
DeniSidorenko, 2020-12-22 07:19:37

How to do actions after State redux is updated?

Good afternoon, working with Redux, I have already encountered this problem 2 times. How to make actions in JS only after the State has been updated. For example, there is a reducer for a cart.
The code is like this

import {
  ADD_TO_CART,
  ADD_QUANTITY,
  SUB_QUANTITY,
  REMOVE_FROM_CART,
  EMPTY_CART,
  UPDATE_PRICE
} from '../actions/actions-types/aside-actions'
let cartInStorage = localStorage.getItem('cart')
let cartInStorageObject = JSON.parse(cartInStorage)
const initialState = {
  cart: cartInStorageObject ||  [],
  totalPrice: 0
}

export default function asideReducer(state = initialState, action) {
  let cart = state.cart
  let cartStringify = JSON.stringify(cart) 
  localStorage.setItem('cart', cartStringify)

  switch (action.type) {
    case ADD_TO_CART:
      let itemInCart = cart.find(item => item.product._id == action.payload.product._id)
      return{ 
        ...state // Example return
      }
    default:
      return state
  }
}


I need to put the cart data in localStorage. But my actions are performed before the action happens. I understand why, because the code executes before the action, but I can’t put it below the switch either, because then it will not be executed ( return will stop the function ). So the question is, where is the best place to track changes and put them in localstorage, because at the moment the code does not write the last click (data) to localstorage, but only from the penultimate one

Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex4answ, 2020-12-22
@DeniSidorenko

Might not get to the heart of your question at all, but storehave subscribean update

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question