AFAF
AFAF

Reputation: 599

React POST request input value is wrong

So I'm trying to add a NewPost and I'm getting the :

"Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component."

...error when it says "this.state.title"

Ps: I'm using nodejs, mongodb and react

e.preventDefault();

  const newPost = {

  title: this.state.title,
  typeOfProduction: this.state.typeOfProduction
  };

Here's my code:

 import React, { Component } from 'react';
 import './NewPost.css';


 class NewPost extends Component {
state = {
    posts:{
        title: '',
        typeOfProduction: ''
    }   
}

postDataHandler(e) {
    e.preventDefault();
    const newPost = {
      title: this.state.title,
      typeOfProduction: this.state.typeOfProduction
    };
    fetch('/projects', {
      method: 'POST',
      body: JSON.stringify(newPost),
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(console.log);

}
render(){

return(
        <div className="Dashboard container-fluid">
        <div className="NewPost">
            <h1>Add a Post</h1>
            <label>Title</label>
            <input type="text" value={this.state.title} name="title" ref="title" onChange={(event) => this.setState({title: event.target.value})} />
            <label>Type of Production</label>
            <select value={this.state.typeOfProduction} name="typeOfProduction" ref="typeOfProduction" onChange={(event) => this.setState({typeOfProduction: event.target.value})}>
                <option value="Fiction">Fiction</option>
                <option value="Tv">TV</option>
                <option value="Tv">Documentary</option>
            </select>

            <button type="submit" onClick={this.postDataHandler}>Add Post</button>
        </div>
    </div>
 );
}
}


export default NewPost;

Upvotes: 0

Views: 55

Answers (1)

Amruth
Amruth

Reputation: 5912

initialize state like this, remove posts.

state = {
     title: '',
    typeOfProduction: ''
}

Upvotes: 2

Related Questions