I am looking at thunk and trying to figure out how to implement an api call. It is not working so I have gone back to the very basics. When I click on the button it shows 'Getting here!
in the console, but nothing is showing when I console.log(dispatch)
. Am I missing something here?
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { connect, Provider } from 'react-redux';
import thunk from 'redux-thunk'
import axios from 'axis';
const store = createStore(
reducer,
applyMiddleware(thunk)
);
function fetchUser() {
return axios.get('https://randomuser.me/api/');
}
function addUser() {
console.log('Getting here');
return (dispatch) => {
console.log(dispatch) //not showing anything
return fetchUser().then(function(data){
console.log(data);
});
};
}
class App extends React.Component {
addUser() {
addUser();
}
render() {
return (
<button onClick={this.addUser.bind(this)}>+</button>
)
}
}
const mapPropsToState = function(store){
return {
newState: store
}
}
var ConnectApp = connect(mapPropsToState)(App);
ReactDOM.render(
<Provider store={store}>
<ConnectApp />
</Provider>,
document.getElementById('app')
)
You cannot call addUser()
from your component as a regular function. You have to use a mapDispatchToProps
function and pass it to your connect
call in order to be able to dispatch addUser()
.
const mapDispatchToProps = dispatch => ({addUser: () => dispatch(addUser())})
then
ConnectApp = connect(mapPropsToState, mapDispatchToProps)(App);
Now you can call it as a prop.
addUser() {
this.props.addUser();
}