// main.jsx --- change the provider
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { Provider } from 'react-redux'
import store from './store/store.jsx'
ReactDOM.createRoot(document.getElementById('root')).render(
// <React.StrictMode>
// <App />
// </React.StrictMode>,
<Provider store={store}>
<App />
</Provider>,
)
// App.jsx --- call the reducer functions using useDispatch and useSelector
import React, {useState} from "react";
import { useDispatch, useSelector } from "react-redux";
import { incrementNum, decrementNum } from "./store/slices/NumberSlice";
function App() {
const [count, setCount] = useState(0);
const numsData = useSelector((state) => {
return state.nums;
})
const dispatch = useDispatch();
const handleNumIncrement = () => {
dispatch(incrementNum(1));
}
const handleNumDecrement = () => {
dispatch(decrementNum(1));
}
return (
<div className="bg-stone-700 h-screen flex">
<div className="mx-auto my-auto flex flex-col text-center space-y-4">
{/* Title */}
<div className="text-slate-50 font-bold text-4xl">Increment / Decrement Counter</div>
{/* Body */}
<div className="text-slate-300 text-2xl">This is a simple app for understanding the use of react redux</div>
{/* Counter */}
<div className="flex flex-row space-x-2 mx-auto border-2 border-stone-900 rounded-xl bg-stone-200">
<button
onClick={handleNumIncrement}
// onClick={()=>(setCount(prev => prev+1))}
className="px-4 py-2 bg-stone-200 hover:bg-stone-400 text-stone-900 rounded-l-xl text-[56px] w-[70px]"
>+</button>
<div
className="px-4 py-2 my-2 w-[100px] text-[48px] rounded-xl bg-stone-500"
>{numsData}</div>
{/* >{count}</div> */}
<button
onClick={handleNumDecrement}
// onClick={()=>(setCount(prev => prev-1))}
className="px-4 py-2 bg-stone-200 hover:bg-stone-400 text-stone-900 rounded-r-xl text-[56px] w-[70px]"
>-</button>
</div>
</div>
</div>
);
};
export default App;
// NumberSlice.jsx --- creating the slices where the reducers are defined
import { createSlice} from '@reduxjs/toolkit';
const numberSlice = createSlice({
name: 'num',
initialState: 0,
reducers: {
incrementNum(state, action){
return state + action.payload;
// state.push(action.payload) // if state was an array
},
decrementNum(state, action){
return state - action.payload;
},
}
})
console.log(numberSlice);
export default numberSlice.reducer;
export const { incrementNum, decrementNum } = numberSlice.actions;
// store.jsx --- saving the store of redux of all the slices
import { configureStore } from "@reduxjs/toolkit";
import numberSlice from "./slices/NumberSlice";
const store = configureStore({
reducer: {
nums: numberSlice,
},
});
export default store;
// File and Folder Structure
root
main.jsx
App.jsx
store -> slices -> NumberSlice.jsx
store -> store.jsx