I am creating a simple counter app using react
and redux
.
The following is the counterSlice.js
file.
import { createSlice } from "@reduxjs/toolkit";
export const counterSlice = createSlice({
name: "counter",
initialState: { count: 0 },
reducers: {
changeValueBy(state, action) {
const value = action.payload;
state["count"] = state["count"] value;
}
}
});
export const { changeValueBy } = counterSlice.actions;
export const selectCount = (state) => state.count;
export default counterSlice.reducer;
The following is the app/store.js
file:
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "../features/counter/counterSlice";
export default configureStore({
reducer: {
counter: counterReducer
}
});
The following is the index.js
file:
import App from "./App";
import store from "./app/store";
import { Provider } from "react-redux"
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
With this setup, the code doesn't work. (Entire code is in this sandbox)
But with following setup, the store
works.
The App.js
file:
import { Counter } from "./features/counter/Counter";
import "./App.css";
import { Provider } from "react-redux";
import { createStore } from "redux";
import counterSlice from "./features/counter/counterSlice";
const store = createStore(counterSlice);
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Provider store={store}>
<Counter />
</Provider>
</header>
</div>
);
}
The entire code is in this sandbox.
I would like to use configureStore
form the @reduxjs/toolkit
package and not the outdated createStore
from redux
package.
Any idea how I can achieve this?
CodePudding user response:
export default configureStore({
reducer: {
counter: counterReducer
}
});
is equivalent to
const store = createStore(combineReducers: {
counter: counterSlice
});
which means that the data from counterSlice
will be found at state.counter
.
Your old code does createStore(counterSlice)
, which means that the data from counterSlice
will be found at state
.
So, both work, but you will have to select the data from different places depending on what you do.
Your selector
export const selectCount = (state) => state.count;
would have to be
export const selectCount = (state) => state.counter.count;
instead.