0

I'm trying to handle simple input value using react-redux and then trying to display it. I know how to display it but i have no idea how to submit input value from component to redux store. I searched web and found nothing. Can someone explain how to do this? I'm totally new to react-redux

import React from "react";
import "./App.css";
import { connect } from "react-redux";
import { useState } from "react";
import { updateValue, addValue } from "./actions/inputActions";

function App(props) {
  const [value, setValue] = useState("");
  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <div className="App">
      <form onSubmit={(value) => props.submitValue(value)}>
        <input onChange={handleChange} value={value} type="text" />
        <button type="submit">Add</button>
      </form>
      <h1>{props.value}</h1>
    </div>
  );
}
const mapStateToProps = (state) => {
  return {
    value: state.value,
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    submitValue: (e, value) => {
      e.preventDefault();
      dispatch(addValue(value));
    },
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(App);

1
  • Please attach code snippets to your question. Show what you tried to do to solve the problem. Commented Apr 16, 2020 at 17:42

1 Answer 1

1

Update your onSubmit function with the value stored in your local state, like this:

<form onSubmit={(e) => {
  e.preventDefault();
  props.submitValue(value)
}}>
  <input onChange={handleChange} value={value} type="text" />
  <button type="submit">Add</button>
</form>

And your mapDispatchToProps function like this:

const mapDispatchToProps = (dispatch) => {
  return {
    submitValue: (value) => {
      dispatch(addValue(value));
    },
  };
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate! I've got 1 more question. How can i add preventDefault here?
Updated the code, you can check the onSubmit method

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.