Search code examples
javascriptreactjsredux-thunk

Value of input field not being changed with Redux thunk


I have simple input field in my component that is connected to store with Redux thunk

import React, {Component} from 'react';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {enterQuantity} from "../../../../store/products.actions";
class SingleProduct extends Component {

    render(){
        const basketDaysQuantity = this.props.basketDaysQuantity;
        return(
<input id="quantity"  type="number" onChange={e => {enterQuantity(e.target.value); console.log(e.target.value)}} value={basketDaysQuantity} />
        )
    }
}

const mapStateToProps = state => ({
    basketDaysQuantity: state.basket.basketDaysQuantity
})

const mapDispatchToProps = (dispatch)  => {
    return {
        enterQuantity: bindActionCreators(enterQuantity, dispatch)
    }
}

I have products.actions file with function that is forwarding action to store

export const enterQuantity = value => dispatch => {
    dispatch({type: ON_QUANTITY_CHANGE, payload: value})
}

and basket.reducer where the value of the input is stored


const initialState = {
    basketDaysQuantity: 1
};
const basketReducer = (state = initialState, action) => {
    switch(action.type) {

case ON_QUANTITY_CHANGE:
            return {
                ...state,
                basketDaysQuantity: action.payload
            }
        default:
            return state;
    }
};

export default basketReduce

but the changes into input field are not reflected, and everything is connected.

Can somebody help?


Solution

  • It looks like you are not getting the enterQuantity function properly, you have to get it from props, try this:

     import React, {Component} from 'react';
        import {connect} from "react-redux";
        import {bindActionCreators} from "redux";
        import {enterQuantity} from "../../../../store/products.actions";
        class SingleProduct extends Component {
        
            render(){
              const {basketDaysQuantity, enterQuantity} = this.props;
                
              return(
                <input 
                   id="quantity"  
                   type="number" 
                   onChange={e => {enterQuantity(e.target.value);            
                 console.log(e.target.value)}} value={basketDaysQuantity} />
                )
            }
        }
        
        const mapStateToProps = state => ({
            basketDaysQuantity: state.basket.basketDaysQuantity
        })
        
        const mapDispatchToProps = (dispatch)  => {
            return {
                enterQuantity: bindActionCreators(enterQuantity, dispatch)
            }
        }