Reputation: 9555
How do I use redux to fire a actionCreator to get my initial data. I need a place to get my initial data when the app loads.
I put it here but actionNoteGetLatest
is not a prop yet.
Please can you help.
componentDidMount() {
// This is where the API would go to get the first data.
// Get the notedata.
this.props.actionNoteGetLatest();
}
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// Redux
import { Provider, connect } from 'react-redux';
// TODO: Add middle ware
// import { createStore, combineReducers, applyMiddleware } from 'redux';
import { createStore } from 'redux';
import { PropTypes } from 'prop-types';
// Componenets
import PageHome from './components/pages/PageHome';
import PageOther from './components/pages/PageOther';
import registerServiceWorker from './registerServiceWorker';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import '../node_modules/font-awesome/css/font-awesome.min.css';
import './styles/index.css';
import rootReducer from './Reducers/index';
import { actionNoteGetLatest } from './actions/noteActions';
// TODO: Turn redux devtools off for production
// const store = createStore(combineReducers({ noteReducer }), {}, applyMiddleware(createLogger()));
/* eslint-disable no-underscore-dangle */
const store = createStore(
rootReducer,
{},
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
);
/* eslint-enable */
class Main extends Component {
// constructor(props) {
// super(props);
// this.state = {
// };
// }
componentDidMount() {
// This is where the API would go to get the first data.
// Get the notedata.
this.props.actionNoteGetLatest();
console.log(this);
}
render() {
return (
<Provider store={store}>
<div className="Main">
<Router>
<Switch>
<Route exact path="/" component={PageHome} />
<Route path="/other" component={PageOther} />
</Switch>
</Router>
</div>
</Provider>
);
}
}
connect(null, { actionNoteGetLatest })(Main);
Main.propTypes = {
actionNoteGetLatest: PropTypes.func.isRequired,
};
ReactDOM.render(<Main />, document.getElementById('root'));
registerServiceWorker();
noteActions.js
import actionTypes from '../constants/actionTypes';
export const actionNoteGetLatest = () => ({
type: actionTypes.NOTE_GET_LATEST,
});
Upvotes: 0
Views: 368
Reputation: 4320
The problem is that you are rendering the initial Main
component instead of the connected one. Update the line with the connect
call to:
const MainWrapper = connect(null, { actionNoteGetLatest })(Main);
Then, use the MainWrapper
component in your render:
ReactDOM.render(<MainWrapper />, document.getElementById('root'));
Check that currently you are rendering the <Main/>
component without providing any prop.
Upvotes: 3