user1941537
user1941537

Reputation: 6695

Passing form variables to action creator in React-Redux

In a React-Redux app, I'm trying to pass the form variable from a component to the action creator without using Redux-Form, Formic or any other extension.

myForm.js

import { connect } from "react-redux";
import { fetchData } from "../actions/myActions";

class myForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      from: "",
      to: ""
    };
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

onFormSubmit(event) {
event.preventDefault();

const from = event.target.elements.from.value;
const to = event.target.elements.to.value;

this.setState({
      from: from,
      to: to
    });

    this.props.fetchData(
      this.state.from,
      this.state.to,
    );
  }

render() {
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
            <div>
            <input
              type="text"
              name="from"
            />
          </div>
          <div>
            <input
              type="text"
              name="to"
            />
          </div>
    </form>
 </div>


    export default connect(
      null,
      { fetchData }
    )(myForm);

I'm passing the action creator fetchData to myForm component and on form submit invoke the onFormSubmit function, which passes the form variables to fetchData like this:

this.props.fetchData(
   this.state.from,
   this.state.to,
);

Then inside myActions.js I try to access those form variables and start an API request.

myActions.js

import { FETCH_DATA } from "./types";
import axios from "axios";
const APP_KEY = <my api key>;

export const fetchData = (from,to) => async dispatch => {
  const response = await axios.get`${URL}/${from}/to/${to}?app_key=${APP_KEY}`;

  dispatch({
    type: FETCH_DATA,
    payload: response.data.journeys
  });
};

Is what I'm trying the right approach? Unfortunately it seems that variables from and to don't get passed to the action creator inside myAction.js.

Upvotes: 0

Views: 18

Answers (1)

Hemant Parashar
Hemant Parashar

Reputation: 3774

setState is an async operation, hence this.props.fetchData is called, before the state is even set. You need to use the callback in the second argument of setStatein myForm.js which is excuted after the state has been updated.

this.setState({
    from: from,
    to: to
}, () => {
    this.props.fetchData(this.state.from,this.state.to)
});

Hope this helps. Happy coding !

Upvotes: 1

Related Questions