Redux-thunk sending does not work

I am looking at thunk and trying to figure out how to implement an api call. It does not work, so I went back to the basics. When I click on the button, it shows 'Getting here!in the console, but nothing is displayed when I am console.log(dispatch). Did I miss something?

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')
)
+4
source share
2 answers

You cannot call addUser()from your component as a normal function. You must use the function mapDispatchToPropsand pass it to your call connectin order to be able to send addUser().

const mapDispatchToProps = dispatch => ({addUser: () => dispatch(addUser())})

then

ConnectApp = connect(mapPropsToState, mapDispatchToProps)(App);

Now you can call it a support.

addUser() {
        this.props.addUser();
    }
+7
source

. . () => {} thunk dispatch.

. mapDispatchToProps connect, App this.props.dispatch(). , App.addUser() this.props.dispatch(addUser()).

- addUser. var ConnectApp = connect(mapPropsToState, {addUser})(App). , this.props.addUser(), .

http://blog.isquaredsoftware.com/2016/10/idiomatic-redux-why-use-action-creators/, gists https://gist.github.com/markerikson/6c7608eee5d2421966d3df5edbb8f05c https://gist.github.com/markerikson/f46688603e3842af0f9720dea05b1a9e.

+2

Source: https://habr.com/ru/post/1666392/


All Articles