DEV Community

Karthikeyan
Karthikeyan

Posted on

Find odd or even number by getting user input using redux

Hi folks today i come up with very popular concet called redux.

Here is the official Documentation for redux --> https://react-redux.js.org/tutorials/quick-start

Here i will show you how to find odd or even number using redux concept

Actually redux is using for very large applications so here i just want to show you in simple way how redux actually works

Here i am using subscribe for enable and disabling the button

function OddorEven() {
    const initialState = { value: 0 , isSubscribed : true }
    const Reduceraction = (state = initialState,action) => {
        if(action.type === 'checkOddorEven')
            {
                if(action.value % 2 === 0)
                {
                    window.alert('even number')
                } else {
                    window.alert('odd number')
                }
            }

        if(action.type === 'subscribe')
        {
            return {
                ...state,
                isSubscribed : !state.isSubscribed
            } 
        } 
        return initialState
    }

    let store = createStore(Reduceraction);

    return (
        <div>
            <Provider store={store}>
            <CheckOddorEven />
            </Provider>
        </div>
    )
}

export default OddorEven

Enter fullscreen mode Exit fullscreen mode

  function CheckOddorEven () {
       const select = useSelector(state => state)    
        console.log('select', select)
        const dispatch = useDispatch()
        const [state, setstate] = useState();
        return (
            <div>
         <input onChange={(e)=>setstate(e.target.value)} />
         <button 
           disabled={select.isSubscribed} 
           onClick={()=> dispatch(checkOddorEven(state))} >
             check
             </button>
         <button 
             onClick={()=>dispatch(subscribe())}> 
                subscribe 
           </button>
            </div>
        )
    }

    export default CheckOddorEven 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)