Mahmud Adam Mahmud Adam - 2 months ago 20
React JSX Question

Getting input value in Redux

I am trying to learn Redux and I am curious to know what I am doing wrong here. I have a simple input field, and I want to dispatch an action to make the text uppercase whenever a change occurs in the input field. Here is my Redux

store
:

const TOCASE = (state="meow", action) => {
switch(action.type){
case 'UPPER':
return state.toUpperCase()
case 'LOWER':
return state.toLowerCase()
default:
return state
}
}
const {createStore} = Redux;
const store = createStore(TOCASE)


Here is my
component
:

const Case = React.createClass({
render(){
return(
<div>
{this.props.text}
<input type="text" value={this.props.text} onChange={this.props.onUpper}/>
</div>
)
}
})


const render = () => ReactDOM.render(<Case
text={store.getState()}
onUpper={(e)=>store.dispatch(e.target.value,{type: 'UPPER'})}
/>, document.getElementById('app'))

render()
store.subscribe(render)

Answer

The first problem is in your ReactDOM.render method where you are dispatching an action :

onUpper={(e)=>store.dispatch(e.target.value,{type: 'UPPER'})}

line should be

onUpper={(e)=>store.dispatch({type: 'UPPER', data : e.target.value})}

The second problem is how you are going to implement this change to you reducer too. Your reducer takes two parameters but that doesn't mean you will dispatch state and action. It means in createStore of Redux , Redux passes state to reducer. Best way to learn this to take a look at Redux createStore. It is a very short piece of code. You will thank yourself later.

So the change in your reducer is :

switch(action.type){
      case 'UPPER':
        return action.data.toUpperCase()
      case 'LOWER':
        return action.data.toLowerCase()
      default:
        return state
  }

A short summary how your reducer works or dispatch works. Why do they take the parameters as I told :

Reducer as I said before is being called in createStore function which you give your reducer as the first parameter. So it takes your reducer and returns an Object of dispatch, subscribe and so on. Basically these functions are references to the functions created in createStore.

Everytime you dispatch an action , you actually call the dispatch function createStore returned, basically you are calling your reducer with this dispatch implicitly. I hope this gives you an idea how things work. Best way to check source code.