import { createSlice, configureStore} from "@reduxjs/toolkit";
const initialState = { counter : 0, showCounter: true };
const counterSlice = createSlice(
{
name: 'counter',
initialState,
reducers: {
increment(state){
state.counter++;
},
decrement(state){
state.counter--;
},
increase(state, action){
state.counter = state.counter + action.payload;
},
toggoleCounter(state){
state.showCounter = !state.showCounter
}
}
}
);
const store = configureStore({
reducer: counterSlice.reducer
});
export const counterActions = counterSlice.actions;
export default store;
import { useState } from 'react';
import { useSelector,useDispatch } from 'react-redux';
import classes from './Counter.module.css';
import {counterActions} from '../store/index'
const Counter = () => {
const counter = useSelector(state => state.counter);
const show = useSelector(state => state.showCounter);
const [value,setValue] = useState(0);
const dispatch = useDispatch();
const incrementHandler = () => {
dispatch(counterActions.increment());
};
const decrementHandler = () => {
dispatch(counterActions.decrement());
}
const onChange = ({target}) => {
if(!target.value){
return;
}else{
setValue(parseInt(target.value))
};
}
const increaseHandler = () => {
dispatch(counterActions.increase(value))
}
const toggleCounterHandler = () => {
dispatch(counterActions.toggoleCounter())
};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
{show && <div className={classes.value}>{counter}</div>}
<input type="text" value={value} onChange={onChange}/>
<div>
<button onClick={incrementHandler}>Increment</button>
<button onClick={increaseHandler}>Increment by inputValue</button>
<button onClick={decrementHandler}>Decrement</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;