Answer the question
In order to leave comments, you need to log in
How to add new value to store using redux hook?
Here is my code
import { createStore, combineReducers } from "redux";
const initalState2 = {
counter: 0
};
function reducer2(state = initalState2, action) {
console.log(state, "action");
switch (action.type) {
case "INCREMENT":
return { ...state, counter: state.counter + 1 };
case "DECREMENT":
return { ...state, counter: state.counter - 1 };
default:
return state;
}
}
export const store = createStore(combineReducers({ reducer2 }));
import React from "react";
import ReactDOM from "react-dom";
import { store } from "./store";
import { Provider } from "react-redux";
import { ExampleComponent } from "./ExampleComponent";
import "./styles.css";
function App() {
return (
<Provider store={store}>
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<ExampleComponent />
</div>
</Provider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React from "react";
import { useDispatch, useSelector, useStore } from "react-redux";
export function ExampleComponent() {
const { counter } = useSelector(state => ({
counter: state.reducer2.counter
}));
const store = useStore();
const dispatch = useDispatch();
return (
<div>
<div>
<button onClick={() => dispatch({ type: "INCREMENT" })}>INCREMENT</button>
Counter: {counter}
<button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
</div>
<button onClick={() => dispatch({ type: "CHECK1" })}>CHeck1</button>
</div>
);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question