React Cannot read property 'name' of undefined on [event.target.name] - javascript

I have a 3rd-party component using Phone Input here https://github.com/bl00mber/react-phone-input-2#react-phone-input-2 I need to get the value input by the user and set the form state using the method below that handles onChange:
const handlePhoneChange = (event) => {
setFormState({
...formState,
[event.target.name]: event.target.value,
});
};
This is my configuration for the 3rd-party component below:
<PhoneInput
country={"us"}
error={hasError("phone")}
helperText={hasError("phone") ? formState.errors.phone[0] : null}
name="phone"
value={formState.values.phone || ""}
onChange={handlePhoneChange}
/>
However, I get the error TypeError: Cannot read property 'name' of undefined when I try to type a number in the phoneInput component. Kindly help me resolve this.

If you read the documentation for the onchange event, there are 4 arguments that are accessible: onChange(value, country, e, formattedValue).
The way you're accessing event is incorrect, because you're accessing the first positional arugment, which is the value of the input. You get an error trying to access event.target since it is not an Event object.
The Event object is available as the third positional argument, so if you use it as such, it should work:
const handlePhoneChange = (value, country, event) => {
setFormState({
...formState,
[event.target.name]: value,
});
};

Related

Uncaught TypeError: Cannot create property 'value' on string

I'm getting this error as soon as I input a second character:
Uncaught TypeError: Cannot create property 'value' on string 'a'
The code so far:
function App() {
const [object, setObject] = useState({
name: "",
value: "",
});
const handleChange = (e) => {
setObject((object) => (object.value = e.target.value));
console.log(object);
};
return (
<div>
<input type="text" onChange={handleChange} placeholder="Type something" />
</div>
);
}
This error occurs because the setState function is not being handled properly here.
Unlike the setState method found in class components, useState does not automatically merge update objects.
So we can say that the real question is:
How to change a single property of a state object using useState hook?
Solution 1: You can return a new object by spreading over previous state.
const handleChange = (e) => {
setObject((prevObject) => ({ ...prevObject, value: e.target.value }));
console.log(object);
};
Solution 2: You can create a new state object and completely replace the old one.
In this solution, you cannot guarantee that object has been refreshed to the latest version.
Also, even if it were, you're setting object to be the same object reference it currently holds, therefore it will not be recognised as a change and the value will not be set.
const handleChange = (e) => {
const temp = object;
temp["value"] = e.target.value;
setObject(temp);
console.log(object);
};
See these questions:
Updating and merging state object using React useState() hook
Cannot create property on string

React Form Field on change function not passing target value to setState

This code could use some improvement, but for now, is there a reason why the name property inside setState cannot access the event e parameter?
//keyObject is a predefined variable
<Form.Control
type="text"
value={this.state.productObject[keyObject].name || ""}
placeholder={"name"}
onChange={(e) => {
this.setState(function (prevState) {
return {
...prevState,
productObject: {
...prevState.productObject,
[keyObject]: {
name: e.target.value,
price: prevState.productObjecy[keyObject].price,
selected: prevState.productObject[keyObject].selected,
},
},
};
});
}}
/>;
When I attempt to change the value of the field, I get the 'Cannot read property 'value' of null' error.
Have you tried
e.target.name.value
An easy way to debug this is to do console.log(e.target) and see what you need next.

Form input field value issue

I am trying to input email value from user and store it in a state variable. I have tried the following code but getting an error:
<Form.Control type="email" required placeholder="Enter email" value={this.state.email} onChange={this.setEmail}></Form.Control>
State variable is defined as follow:
this.state = {
email: '',
}
Following is my code to set the value entered by user in email:
setEmail = (e) => {
this.setState(() => ({email: e.target.value}))
}
I tried printing e.target.value. It is correct. But while running this code, I am getting error:
Cannot read property 'value' of null
Any comments on how to fix this issue?
That is happening because the event is not persisted, and it is used in an asynchronous function (setState is async).
Just extract it before calling setState.
setEmail = (e) => {
const {value} = e.target;
this.setState(() => ({email: value}))
}

Not being able to set state for a selected date from a DatePicker

So I am having trouble with setting the state for the date selected from this DatePicker
change:
change = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
DatePicker component:
<DatePicker
selected={this.state.startDate}
onChange={e => this.change(e)}
/>
If I use the default date when you first reload the page, there is no issue. But it's when a date is selected that I get an error.
A Type Error: Cannot read property 'name' of undefined.
 
What am I doing wrong?
The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.
More information can be found here.
Since setState is asynchronous the event will be null by the time it's evaluated in setState.
Instead, deconstruct the event before setState:
change = ({ target: { name, value } }) => {
this.setState({
[name]: value,
});
}
or
change = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
}

TypeError: Cannot read property 'name' of null

I have a user object where they are able to edit their info (phone number, email, etc)
I am unable to access the input's name inside the setState callback and keep getting TypeError: Cannot read property 'name' of null
However when I log the event.target.name it shows to be there.
When I change a simple state it works:
Assuming the state value is the same as the target name.
this.setState({ [event.target.name]: value });
I am following this post to update the user object.
Sorry if this is a duplicate, I could not find what I was looking for.
handleUserChange(event) {
console.log(event.target.name);
const value = event.target.value
this.setState(prevState => ({
user: {...prevState.user, [event.target.name]: value }
}))
}
Edit: I am binding it properly in the class constructor like so:
contructor(props) {
super(props);
...
this.handleUserChange = this.handleUserChange.bind(this)
}
React is recycling this event. So the async call to setState wont know the value of event.target.name since the event is already gone. You need to make a copy of the value the same as you did with event.target.value.
handleUserChange(event) {
console.log(event.target.name);
const name = event.target.name;
const value = event.target.value;
this.setState(prevState => ({
user: {...prevState.user, [name]: value }
}))
}
From the docs: link
Other solution:
handleUserChange(event) {
event.persist();
const value = event.target.value;
this.setState(prevState => ({
user: {...prevState.user, [event.target.name]: value }
}))
}
Persists the values of the event.

Categories

Resources