简体   繁体   中英

How can I pass state to action to fetch API?

so im new in redux and I need bit of help with my homework. I have a drop down with couple of choices and the choice that user select needs to be passed to state (already have this working and state is updating when user select something new) and then to action that can fetch data with '/stats/${userChoice}' . But i have no idea how to do this at all.

actions/index.js:

export const fetchAuthorsStats = () => async dispatch => {
    const response = await myAPI.get(`/stats/${userChoice}`);

    dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};

components/Dropdown.js:

onAuthorSelect = (e) => {
        this.setState({selectAuthor: e.target.value})
    };

.
.
.

const mapStateToProps = state => {
    return {
        authors: state.authors,
        selectAuthor: state.selectAuthor,
        authorsStats: state.authorsStats
    }
};


export default connect(mapStateToProps, { fetchAuthors, selectAuthor, fetchAuthorsStats })(Dropdown)

under "selectAuthor" I have my state that I need to pass to this action API

You can achieve this by calling the API directly with the event target value :

/// first you update your API call to receive the selected author
export const fetchAuthorsStats = (userChoice) => async dispatch => {
    const response = await myAPI.get(`/stats/${userChoice}`);

    dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};

//then you update your handler function

onAuthorSelect = (e) =>{
this.props.fetchAuthorsStats(e.target.value)
}

if you wish to still save it on the react state you can do the setState first and then the API call with (this.state.selectedAuthor) instead of (e.target.value)

You already map dispatch to fetchAuthorsStats thunk in your component so that means you can just use it in onAuthorSelect (or anywhere else you need - like on form submit) and pass it a parameter with the selectedAuthor.

// Added a userChoice param here:
export const fetchAuthorsStats = (userChoice) => async dispatch => {
    const response = await myAPI.get(`/stats/${userChoice}`);

    dispatch({ type: 'FETCH_AUTHORS_STATS', payload: response.data })
};

onAuthorSelect = (e) => {
  this.setState({selectAuthor: e.target.value})    
  this.props.fetchAuthorsStats(e.target.value);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM