1

I am developing a small project to learn react redux, I had a good view of connecting react with redux. I am trying to perform a small task that is clearing the input box after hitting submit, I've tried using reset, wrote separate function to clear the state and included the logic to clear input in handleSubmit handler itself, I didn't get the expected output. Can anyone guide me how to achieve this. Thanks in advance.

AddRemainder.js File : 

import React, { Component } from "react";
import { connect } from "react-redux";
import addRemainder from "../../redux/action.js";

class AddRemainderPage extends Component {
  state = {
    reminder: {
      title: "",
    },
  };

  handleChange = (e) => {
    const reminder = { ...this.state.reminder, title: e.target.value };
    this.setState({ reminder });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.dispatch(addRemainder(this.state.reminder));
      
  };

  render() {
    return (
      <div className="App">
        <div>
          <h2>My First Redux UnderStanding</h2>
          <form onSubmit={this.handleSubmit}>
            <input
              type="text"
              onChange={this.handleChange}
              value={this.state.reminder.title}
            />

            <input type="submit" value="Save" />
          </form>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    reminderss: state.reminderss,
  };
};

export default connect(mapStateToProps)(AddRemainderPage);

Action.JS File:

const addRemainder = (text) => ({
  type: "ADD_REMINDER",
  rem: text,
});

export default addRemainder;

Reducer.JS File:

const intialState = {
  reminderss: [],
};

const remindersReducer = (state = intialState, action) => {
  switch (action.type) {
    case "ADD_REMINDER":
      return {
        reminderss: [...state.reminderss, action.rem],
      };
    default:
      return state;
  }
};

export default remindersReducer;

1 Answer 1

3

Try this way:

clearInput = () => {
const reminder = { ...this.state.reminder, title: '' };
this.setState({ reminder });
};

handleSubmit = (e) => {
e.preventDefault();
this.props.dispatch(addRemainder(this.state.reminder));
this.clearInput();
};
Sign up to request clarification or add additional context in comments.

2 Comments

thank you it's working. If I am adding more than 5 values in state shall I do like below ? const reminder = { ...this.state.reminder, title: '', abc:"", xyz:"", };
Yeah, same way you can do it for N number of input fields

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.