import React, { Component } from 'react' import axios from 'axios' import constant from '../service/constant'; class CreatePost extends Component { constructor(pros){ super(pros) this.state = { title:'', content:'', image:'', courses:[], course:'', } } changeHandler = (e) => { const state = this.state state[e.target.name] = e.target.value; this.setState(state) } userTypeHandler = (e) => { const state = this.state state[e.target.name] = e.target.value; this.setState(state) } componentDidMount() { axios.get(constant()+'/courses').then( data => { this.setState({ courses: data.data, course:data.data[0].id //get first object id from courses list and set status to defult course }) } ).catch(error => { console.log(error) }) } submitHandler = (e) => { e.preventDefault() console.log(this.state) axios.post(constant()+'/save/post', this.state) .then(response => { console.log(response) if(response.data !== ''){ alert(`Post added successfully`); this.props.history.push("/createpost") } }) .catch(error => { console.log(error) }) } SubmitButtonHandler = () => { this.props.history.push("/createpost") } render(){ const { title,image, content,course} = this.state; return ( <div className="container"> <div className="panel panel-default"> <div className="panel-heading"> <h3 className="panel-title"> Create New Post </h3> </div> <div className="panel-body"> <form onSubmit={this.submitHandler}> <div className="form-group"> <label>Title:</label> <input type='text' id="title" className="form-control" name="title" value={title} onChange={this.changeHandler} placeholder="Title" pattern="^[a-zA-Z0-9_]+$" title="Title is required"/> </div> <div className="form-group"> <label>Content:</label> <textarea className="form-control" name="content" value={content} onChange={this.changeHandler} placeholder="Content" /> </div> <div className="form-group"> <label>Image:</label> <input type='text' className="form-control" name="image" value={image} onChange={this.changeHandler} placeholder="Image" /> </div> <div className="form-group"> <label>Course:</label> <select className="form-control" name="course" onChange={this.changeHandler} value={course}> { this.state.courses.map(sub => { return ( <option key={sub.id} value={sub.id}>{sub.cname}</option> ) }) } </select> </div> <button type="button" className="btn btn-outline-secondary loginBtn" onClick={this.SubmitButtonHandler}>Submit</button> </form> </div> </div> </div> ); } } export default CreatePost;