M
M
Mykhailo Nikolaiev2020-10-28 06:16:54
React
Mykhailo Nikolaiev, 2020-10-28 06:16:54

How to store input from input in state?

Why doesn't save input from input in state?

import React, { Component } from 'react';
import { connect } from 'react-redux';
import T from 'prop-types';

import { addContact } from '../../redux/Contacts/contactActions';

import styles from './Phonebook.module.css';
import inputPhoneId from '../../helpers/inputPhoneId';

class Phonebook extends Component {
  state = {
    contactName: '',
    contactNumber: '',
  };

  static propTypes = {
    onSubmit: T.func.isRequired,
  };

  handleChange = e => {
    const { value } = e.target;
    this.setState({ contactName: value, contactNumber: value });
  };

  handleSubmit = e => {
    const { name, number } = e.target;
    e.preventDefault();

    const { contactName, contactNumber } = this.state;
    const { onSubmit } = this.props;

    console.log(onSubmit(contactName, contactNumber));

    this.reset();

    name.value = '';
    number.value = '';
  };

  reset = () => {
    this.setState({
      contactName: '',
      contactNumber: '',
    });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit} className={styles.form}>
        <label htmlFor={inputPhoneId.name} className={styles.label}>
          Name
          <input
            type="text"
            name="name"
            placeholder="Enter contact name..."
            mask="+99(999)999-99-99"
            id={inputPhoneId.name}
            onChange={this.handleChange}
            className={styles.input}
          />
        </label>
        <br />
        <label htmlFor={inputPhoneId.number} className={styles.label}>
          Number
          <input
            type="text"
            name="number"
            placeholder="Enter contact number..."
            id={inputPhoneId.number}
            onChange={this.handleChange}
            className={styles.input}
          />
        </label>
        <br />

        <button type="submit" className={styles.btn}>
          Add contact
        </button>
      </form>
    );
  }
}

const mDTP = () => ({
  onSubmit: addContact,
});

export default connect(null, mDTP)(Phonebook);


action:
export const addContact = (name, number) => ({
  type: ActionType.ADD_CONTACT,
  payload: { name, number, id: uuidv1() },
});


reducer:
const contactsReducer = (state = [], { type, payload }) => {
  switch (type) {
    case ActionType.FETCH_CONTACTS:
      return payload;

    case ActionType.ADD_CONTACT:
      return [...state, payload];

    case ActionType.DELETE_CONTACT:
      return state.filter(item => item.id !== payload);

    default:
      return state;
  }
};

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question