I am learning React. I thought this will be a very simple task but I am stuck in issuing a dispatch on the store after axios promise is complete.
This is the source code of my entire class.
Inside the promise, the value of store is undefined. I have tried a lot of combinations. In Angular I can just define a class variable and can use it. What should I do here?
class CricketScorer extends Component {
constructor(props, context) {
super(props, context);
const { store } = this.context;
this.isLoading = false;
}
componentDidMount() {
console.log('Get Initial State from Server');
axios.get(jsonURL)
.then((response) => {
console.log('axios.get SUCCESS', response.data);
console.log('componentDidMount Value Of Store', this.store);
this.store.dispatch({
type: constants.INITIAL_STATE,
payload: response.data
});
})
.catch(error => {
console.log('axios.get ERROR', error);
});
}
render() {
console.log('Cricketscorer render()', this.store)
// This function always recieve single argument [this.props]
// All other passed values are as "this.props.recipes"
return (
<div>
<ScoreBoard />
<ScoreAction />
{this.isLoading === true && <span>Loading...</span>}
</div>
);
}
}
The console output is:
Navigated to http://localhost:3000/
Cricketscorer render() undefined
Scoreboard state Object {matchId: 0, thisOver: Array(0), prevOver: Array(0), oversTotal: 0, teamBatting: Object…}
Get Initial State from Server
axios.get SUCCESS Object {matchId: 100, thisOver: Array(0), prevOver: Array(0), oversTotal: 0, teamBatting: Object…}
componentDidMount Value Of Store undefined
axios.get ERROR TypeError: Cannot read property 'dispatch' of undefined
As you can see I am trying to issue a dispatch and it is giving me error there saying:
axios.get ERROR TypeError: Cannot read property 'dispatch' of undefined