Search code examples
reactjsreduxreact-reduxredux-toolkit

Redux toolkit state property that is dependent on other state property


With redux toolkit what is the correct way of defining one state property that is dependent on other state property? I need something like:

const initialState: AppSliceState = {
  words: "",
  cursor: 0,
 ** typedChars: words.substring(0, cursor),
  remainingChars: words.substring(cursor, words.length - 1),**
};

In my app I fetch some text from api and put it in words property. Then when user starts typing, cursor property is increased on every typed key. For example if fetched words is "Hello!" and user press H then cursor becomes 1 and typedChars should be "H", and remainingChars should be "ello!"

I think I can define typedChars in my App component but in that case I may have props drilling which I would like to avoid


Solution

  • This seems like a use case for createSelector, as you are deriving data:

    https://redux.js.org/usage/deriving-data-selectors

    const selectWords = state => state.words
    const selectCursor = state => state.cursor
    
    const selectTypedChars = createSelector([selectWords, selectCursor], (words, cursor) => {
        return words.substring(0, cursor)
    })
    
    const selectRemainingChars = createSelector([selectWords, selectCursor], (words, cursor) => {
        return words.substring(cursor, words.length - 1)
    })
    

    and then where you need it you can just do

    const typedChars = useSelector(selectTypedChars)