SetState Inside ComponentDidmount Is Throwing Error
I am new to React JS and have started to create a small application in it. I'm facing some issue in SetState
inside componentDidmount
method.
I have a parent/home component, from where I would call a child component and pass an Id
as a prop. Based on the id, an API call will be sent. After getting the required data from callback, I need to set the data retrieved it in the input box as value.
Error:
" A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. "
Code used:
Child Component:
import React from 'react';
class EditTodo extends React.Component {
constructor(props){
super(props);
this.onChangeTodoId = this.onChangeTodoId.bind(this);
this.state={
Todo_Id:''
}
}
componentDidMount(){
fetch('http://localhost:4000/todo/'+this.props.match.params.id)
.then(response => response.json())
.then(data => {
this.setState({
Todo_Id: data.Todo_Id
})
})
.catch( (error)=>{
console.log(error);
})
}
onChangeTodoId(e){
this.setState({
Todo_Id: e.target.value
});
}
render() {
return (
<div>
<form>
<div className="form-group">
<label>ID: </label>
<input
type="text"
className="form-control"
value={this.state.Todo_Id}
onChange={this.onChangeTodoId}
/>
</div>
</form>
</div>
);
}
}
export default EditTodo;
Answer
React has 2 types of inputs: controlled or uncontrolled. controlled inputs receive a value trough the value attribute (more info here)
Your code seems fine but in this case your data.Todo_Id is likely undefined, which causes the error. Did you try to log the output of your api response?
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM