0

I have a React app that can be embedded several times on a single html page. Each time the html tag can come with a different data-* attribute that is used for initialisation of the app:

<div class="my-app" data-my-config="SOME_ENCODED_JSON_PROPERTIES" />

Depending on the passed SOME_ENCODED_JSON_PROPERTIES the app's redux store is to be initilized with a different initialState. Reading the docs and examples on initialState, the initialState is always set from some static const variables - how can it be set at "runtime" passed on the initial data-my-config attribute?

nachtigall
  • 2,447
  • 2
  • 27
  • 35

1 Answers1

1

Examples can only show basics - it's important to extrapolate what's possible based on those.

In this case, the key is that you have to have the data available, in scope, at the time that you call createSlice(). How you get that value and where it comes from is up to you.

If that's not feasible given your architecture, then you can always provide a placeholder initial state, and then either:

  • Override that value by providing a preloadedState argument to configureStore that contains data for this slice
  • Define an reducer in the slice that replaces its state with the action payload, and dispatch that action after the initial store is created
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • Thanks for answering, sorry if I sounded offensive regarding the examples, I rather just wanted to make clear that I already searched the web and docs quite a bit. Yeah, the data is not in scope when calling `createSlice`, that's the problem. Will look into `preloadedState`... Anyway, by accident I came across https://stackoverflow.com/questions/60999058/load-initialstate-dynamically-with-createslice-in-redux-toolkit just now which seems to give another 3rd option. Though, it sounds more of a workaround. – nachtigall Jun 14 '21 at 15:05
  • So, going the `preloadedState` path does not seem to work bc `configureStore` also needs to run at initialisation (but I need it to run at DOMContentLoaded, so data is available) due to TypeScript and https://github.com/reduxjs/redux-toolkit/issues/651#issuecomment-658193473 Well, so in the end only the 2nd option with creating "initial reducers" for all slices seem to be the only option if I am correct :-/ – nachtigall Jun 15 '21 at 14:21