Ad

SetState Inside ComponentDidmount Is Throwing Error

- 1 answer

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;
Ad

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?

Ad
source: stackoverflow.com
Ad