Redux Toolkit - Copy data from one slice to another

Viewed 68

I have a redux store configured using redux-toolkit with two slices: products and cart.

export const store = configureStore({
  reducer: {
    products: productsReducer,
    cart: cartReducer,
  },
})

I would like to copy some data from the products slice into the cart slice when the user clicks an "Add to cart" button in the UI. This data will include the product ID and quantity which is currently set in the products slice. I'd like to dispatch an action that copies that data across, instead of having to pull the data out into a component and then pass it back in through the dispatched action. Is this possible with redux toolkit? Is this a use-case for a thunk?

1 Answers

Duplicating data goes against the idea of redux having a 'single source for truth' and is not recommended.

If I understand you correctly, you say you want to do the duplication (modifying the state) without dispatching that data through actions. This goes against the principle of immutability and pure functions on which redux is based.

TLDR: Redux is based on the idea of modifying a single state (with no duplication) through pure functions. Your use case goes against it all.

Related