Rayan
Rayan

Reputation: 73

state in my react app get set to undefined

Below is my code for a personal project where i can keep track of my monthly subscriptions, if i have to add a subscription i just have a add an object to an existing array. however for testing purposes when i tried to console.log(value.startDate) in handleSubmit it gives me undefined and causes further problems. How would i fix it?

import React from 'react';
import PropTypes from 'prop-types';
const List = () => {
    const [ mylist, setList ] = React.useState([]);
    const [ value, setValue ] = React.useState({ subscription: '', startDate: '', paymentTime: 0 });
    const handleSubmit = (e) => {
        console.log(value.startDate);
        setList(mylist.push(value));
        e.preventDefault();
    };
    const handleOnChange = (event) => {
        setValue({ [event.target.name]: event.target.value });
    };
    return (
        <div>
            <div className="for_list">
                <ul className="list">{mylist.map((obj) => <li key={obj.subscription}>{obj.subscription}</li>)}</ul>
            </div>
            <div className="for_form">
                <form>
                    <input type="text" name="subscription" onChange={handleOnChange} value={value.subscription} />
                    <input type="text" name="startDate" onChange={handleOnChange} value={value.startDate} />
                    <input type="number" name="paymentTime" onChange={handleOnChange} value={value.paymentTime} />
                </form>
            </div>
            <button onClick={handleSubmit}>Add Item</button>
        </div>
    );
};
// it just removes the error above.
List.propTypes = {
    list: PropTypes.node
};
export default List;

Upvotes: 0

Views: 108

Answers (2)

Ezzat
Ezzat

Reputation: 911

On handleChange function you need to pass the old value of value

 const handleOnChange = (event) => {
    setValue({ ...value , [event.target.name]: event.target.value });
 };

Upvotes: 1

Panther
Panther

Reputation: 9408

You are replacing your state every time. This might be because of the miss in understanding the difference between setState in traditional class based React components and useState.

You need to append the value to the existing data. Something similar would work

const handleOnChange = (event) => {
    setValue({ ...value, [event.target.name]: event.target.value });
};

The setState in class based components always accepts partial state and merges with the existing one. While useState setter function replaces the value you provide in the respective state.

Upvotes: 1

Related Questions