Search code examples
javascriptreactjsreduxreact-redux

React+Redux | Prop Returns Undefined Here - Why?


I recently learned some basic Redux and went over the tutorial on their docs.

I have a React presentational class component that I want for it to also be its own container components, named Word.

I want its props' values to come from the Redux store. I was able to successfully get initial values for its props from the initial state of the store, but when I try to dispatch an action, its property wordParts returns undefined.

This is the structure of the Word:

Word : {
  wordParts : <array>
  stem : <object> //I'm using a string for now for testing
}

This is the structure of the store:

store : {
  word : {
    wordParts : <array>
    stem : <object> //I'm using a string for now for testing
  }
}

This is what I want the actions to do when they're dispatched:

//is used to update Word.stem
replaceStem(stem) = currentStem => newStem 

//is used to add a some `suffix` variable as the last element of the current Word.wordParts
addSuffix(suffix) = currentWordParts => [...currentWordParts, suffix] 

This is my code - I have some other non-relevant code, I changed it a bit to remove irrelevant code (such as styling), but it should behave the same as my local code.

https://codesandbox.io/s/rj2xlryx8m


Solution

  • Solution found + explanation:

    Explanation: The component got its props from the class, so it did get initialized correctly, as when the an instance of that class called in its constructor to props taken from the store. Those initial states kept being stored as properties of the class, and when accessed as properties of the object, the returned values were the same ones that were stored in the class.

    The solution: Remove/not use those props as class properties, and instead call them from the render() function that gets recalled on changes to the component (in this case, change in its props, that is made by mapStateToProps, which is triggered by a change in the Redux store).