I am completely stumped on this one. I've built the simplest of simple react redux component that currently only shows a counter held in the store. However this counter is always returned as undefined!
I'd expect the counter to return 0
as this is what's set in the reducer!
I've followed countless tutorials and I'm getting no where!
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import counterReducer from './reducers/counterReducer';
const store = createStore(counterReducer);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
and
//app.js
import React from 'react';
import { useSelector } from 'react-redux';
function App() {
const counter = useSelector(state => state.counter)
return (
<div className="App">
<p>{`counter is ${counter}`}</p>
</div>
);
}
export default App;
and
//actions.js
export const add = (nr) =>{
return {
type: 'ADD',
payload:{
nr
}
}
}
and
//counterReducer.js
const counterReducer = (state=0, action) => {
switch(action.type){
case "ADD":
return state+1;
default:
return state;
}
}
export default counterReducer;
So as you can see it's a real simple setup. I'd expect the counter to return 0
as this is the initial state set in counterReducer.js
However I just get "counter is undefined" on the frontend!
either remove .counter
from state
// already a number
const counter = useSelector(state => state)
or add counter
to your redux root object:
import {createStore, combineReducers } from 'redux';
import counterReducer from './reducers/counterReducer';
const store = createStore(combineReducers({counter: counterReducer});