I'm trying to input text to innerState.feedType. but when i tried it says Cannot read property 'toString' of undefined How can i fix my code?
this is my code
const [innerState, setInnerState] = useState<any>({
feedType: 'bbong',
})
const onChangeEtcfeedtype = useCallback((text) => {
setInnerState( innerState['feedType'] = text)
},[]);
<TextInput
placeholder="input."
value={innerState.feedType}
onChangeText={onChangeEtcfeedtype}
/>
CodePudding user response:
I think this is how you should write it.
About the error. It look like its not come from this part. It come from your <TextInput />
component and possiblely caused because what you doing with onChange event
.
const [innerState, setInnerState] = useState<any>({
feedType: 'bbong',
})
const onChangeEtcfeedtype = useCallback((text) => {
setInnerState({feedType: text})
},[]);
<TextInput
placeholder="input."
value={innerState.feedType}
onChangeText={onChangeEtcfeedtype}
/>
Please do consider read these article:
https://stackoverflow.com/help/how-to-ask
CodePudding user response:
Here, innerState['feedType'] = text
you are changing the state directly and then store it using the updater function, you should not change it directly.
You have innerState which is object and it contains feedType property. So, update a state you have to pass the object with the same key with new value.
Correct Way:
setInnerState({feedType: text})
CodePudding user response:
You need to add null-safety(?) operator, because state creates after render components. Also need to return new link on object for re-render component.
const [innerState, setInnerState] = useState<any>({
feedType: 'bbong',
})
const onChangeEtcfeedtype = (text) => {
setInnerState({...innerState, innerState.feedType: text});
};
<TextInput
placeholder="input."
value={innerState?.feedType}
onChangeText={onChangeEtcfeedtype}
/>