Reputation: 2381
I'm trying to add redux to my react app.
My index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, compose, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import dashboardReducer from './store/reducer/dashboard';
const rootReducer = combineReducers({
dashboard: dashboardReducer
});
const store = createStore(rootReducer);
const app = (
<Provider store={store}>
<App />
</Provider>
)
ReactDOM.render(
<React.StrictMode>
{app}
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Then, I have a store folder with actions folder and reducer folder. In my actions folder, I have the actionsType.js:
export const TEST = 'TEST';
I also have the dashboard.js:
import * as actionTypes from './actionsTypes';
export const test = () => {
return {
type: actionTypes.TEST
}
};
And finally, the index.js to return the actions:
export {
test
} from './dashboard';
Inside the reducer folder, I just have one reducer now, called dashboard.js
import * as actionTypes from '../actions/actionsTypes';
const initialState = {
counter: 0
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.TEST:
return {
...state,
counter: state.counter++
};
default:
return state;
}
};
export default reducer;
I create, in my components folder, a test class Dashboard.js to test my redux.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as action from '../store/actions/index';
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
render() {
return (
<div>
<h2>Main Page: {this.props.ctr}</h2>
<button onClick={this.props.onTest}>TEST</button>
</div>
);
}
}
const mapStateToProps = state => {
return {
ctr: state.counter
};
};
const mapDispatchToProps = dispatch => {
return {
onTest: () => dispatch(action.test())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
When I open the page, it just say "Main Page: ". Shouldn't it start with a 0 value? Also, When I click on the button "test", nothing changes.
Sorry, I'm just starting with react and redux, I'm probably missing a lot of configuration.
Thanks
Upvotes: 0
Views: 76
Reputation: 4518
Try this:
BEFORE
const mapStateToProps = state => {
return {
ctr: state.counter
};
};
AFTER
const mapStateToProps = state => {
return {
ctr: state.dashboard.counter
};
};
Upvotes: 1
Reputation: 2942
You're not getting the value from the correct reducer. A nice way to debug that is logging the state inside the mapping:
const mapStateToProps = state => {
console.log(state); // This will run with EVERY state change
return {
ctr: state.counter
};
};
Since you named your reducer as dashboard
, just call it there:
const mapStateToProps = state => {
return {
ctr: state.dashboard.counter
};
};
Upvotes: 2