0

I built an input interface in React and stored the data in a Redux state.

Then, I created a new action for a Post API call. If the "data" parameter is a constant (that I created as a test), everything works fine.

In reality, I'd like to use a key from the Redux state as the data parameter.

In the example, I'm getting an error because props are not defined. Does it makes sense to connect this action to the state? If yes, how to do it? Thanks a lot!

import axios from 'axios';

export const show_query_action = () => {
  return dispatch => {
    dispatch(show_query_started_action());
    axios({
      method: 'post',
      url:'http://127.0.0.1:5000/show_query',
      data: this.props.reducer_components
    })
      .then(res => {
        dispatch(show_query_success_action(res));
      })
      .catch(err => {
        dispatch(show_query_failure_action(err.message));
      });
  };
};

const show_query_started_action = () => ({
  type: 'ADD_SHOW_QUERY_STARTED'
});

const show_query_success_action = todo => ({
  type: 'ADD_SHOW_QUERY_SUCCESS',
  payload: {
    ...todo
  }
});

const show_query_failure_action = error => ({
  type: 'ADD_SHOW_QUERY_FAILURE',
  payload: {
    error
  }
});

1 Answer 1

1

If it needs to be callable with different parameters from a React component you can put the data parameter as a parameter to your action creator:

export const show_query_action = (data) => {
  return dispatch => {
    dispatch(show_query_started_action());
    axios({
      method: 'post',
      url:'http://127.0.0.1:5000/show_query',
      data: data
    })

This is also easily testable. If you only call this action with parameters from the redux store, you can use the second parameter from redux-thunk (wich i presume you are using here):

export const show_query_action = () => {
  return (dispatch, getState) => {
    const data = getState().data; -> you would specify in wich part of the state your data lives, this is just an example
    dispatch(show_query_started_action());
    axios({
      method: 'post',
      url:'http://127.0.0.1:5000/show_query',
      data: data
    })

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.