I have a problem and I am ensure this is my problem setusername(res.data[0].username)
So basically I watch MERN stack tutorial and I was at my this part 1:27:30. Basically It means to I want to pass my data username based on my list of users in creating exercises. Everything is fine but not only this setusername(res.data[0].username)
Here is the full code.. for Create_exercises()
NOTE I CONVERTED THE CLASS COMPONENT INTO REACT HOOKS SINCE IT KINDA LOOKS UGLY IN MY EYE
function Create_exercise() {
const [username,setusername] = useState()
const [description,setdescription] = useState()
const [duration,setduration] = useState()
const [date,setdate] = useState( new Date() )
const [users, setusers] = useState([])
const handleChangeUsername = e => {
setusername(e.target.value)
}
const handleChangeDesciption = e => {
setdescription(e.target.value)
}
const handleChangeDuration = e => {
setduration(e.target.value)
}
const handleChangeDate = date_new => {
setdate(date_new)
}
const handleSubmit = e => {
e.preventDefault()
const exercise = {
username: username,
description: description,
duration:duration,
date:date
}
console.log(exercise);
axios.post('http://localhost:4500/exercises/add',exercise)
.then(res => console.log(res.data))
.catch(err => console.log(err));
// window.location = '/';
}
useEffect(() => {
// setusers(['test user'])
// setusername('test user')
axios.get('http://localhost:4500/users/')
.then(res => {
if (res.data.length > 0) {
// console.log(users)
// console.log(res.data)
setusers(res.data.map((user => user.username)))
setusername(res.data[0].username)
// console.log(res.data[0].username)
}
})
},[])
return (
<div className='form-container'>
<form action="" onSubmit={e => handleSubmit(e)}>
<div className="title"><h1> Create New Exercise Log</h1></div>
<div className="form-group">
<label htmlFor="">Username: </label>
<select name="" id="">
{
users.map((user,idx) => {
return(
<option
key={user}
value={user}
>
{user}
</option>
)
})
}
</select>
</div>
<div className="form-group">
<label htmlFor="">Description: </label>
<input type="text"
required
className='form-control'
value={description}
onChange={e => handleChangeDesciption(e)}
/>
</div>
<div className="form-group">
<label htmlFor="">Duration (in minutes): </label>
<input type="text"
required
className='form-control'
value={duration}
onChange={e => handleChangeDuration(e)}
/>
</div>
<div className="form-group">
<label htmlFor="">Date: </label>
<div>
<DatePicker
selected= {date}
onChange= {e => handleChangeDate(e)}
>
</DatePicker>
</div>
</div>
<div className="form-group">
<input type="submit" value="Create Exercise Log"/>
</div>
</form>
</div>
)
}
export default Create_exercise
Let say I have 3 items in data that in my mongoDB.. Let say data = [{username:"Johnny",_id:"613fagadafa43d",description:"Egg"},{username:"Lamby",_id:"613dasnaafaF",description:"Betlog"},{username:"Bummby",_id:"613d66naafaF",description:"Betlog"}]
when I am trying to create a exercise that I will choose based on this three.. I always create the first item in data list. So it has something to with this setusername(res.data[0].username) since it is the first index.. I want to create a exercise wherein I can choose whose name should I create the data but I always get this thingy "Johnny" name in the data.. I wanna badly done this so I could understand how mern stack works..I'm so confused..help.
This is also same with Edit_exercise() based on the tutorial of MERN stack at part of MERN 1:45:06
Sorry I'm so bad at this explaining but this is just how I will imagined and describe the problem..I know its kinda simple but I don't know if I ask the right question.
function Edit_exercise() {
const { id } = useParams()
const [username,setusername] = useState()
const [description,setdescription] = useState()
const [duration,setduration] = useState()
const [date,setdate] = useState( new Date() )
const [users, setusers] = useState([])
const handleChangeUsername = e => {
setusername(e.target.value)
}
const handleChangeDesciption = e => {
setdescription(e.target.value)
}
const handleChangeDuration = e => {
setduration(e.target.value)
}
const handleChangeDate = date_new => {
setdate(date_new)
}
const handleSubmit = e => {
e.preventDefault()
const exercise = {
username: username,
description: description,
duration:duration,
date:date
}
console.log(exercise);
axios.put('http://localhost:4500/exercises/update/'+id,exercise)
.then(res => console.log(res.data))
.catch(err => console.log(err));
// window.location = '/';
}
useEffect(() => {
axios.get('http://localhost:4500/exercises/'+id)
.then(res => {
setusername(res.data.username)
setdescription(res.data.description)
setduration(res.data.duration)
setdate(new Date(res.data.date))
})
setusers(['test user'])
setusername('test user')
axios.get('http://localhost:4500/users')
.then(res => {
if (res.data.length > 0) {
setusers(res.data.map((user => user.username)))
setusername(res.data[0].username)
}
})
},[])
return (
<div className='form-container'>
<form action="" onSubmit={e => handleSubmit(e)}>
<div className="title"><h1> Edit Exercise Log</h1></div>
<div className="form-group">
<label htmlFor="">Username: </label>
<select name="" id="">
{
users.map((user,idx) => {
return(
<option
key={user}
value={user}
>
{user}
</option>
)
})
}
</select>
</div>
<div className="form-group">
<label htmlFor="">Description: </label>
<input type="text"
required
className='form-control'
value={description}
onChange={e => handleChangeDesciption(e)}
/>
</div>
<div className="form-group">
<label htmlFor="">Duration (in minutes): </label>
<input type="text"
required
className='form-control'
value={duration}
onChange={e => handleChangeDuration(e)}
/>
</div>
<div className="form-group">
<label htmlFor="">Date: </label>
<div>
<DatePicker
selected= {date}
onChange= {e => handleChangeDate(e)}
>
</DatePicker>
</div>
</div>
<div className="form-group">
<input type="submit" value="Edit Exercise Log"/>
</div>
</form>
</div>
)
}
export default Edit_exercise
Related
i was trying to make a restaurant review application using mern stack but in the frontend , i keep getting a problem in the react.
The pages load perfectly in the main page where the code as follows
import React, { useState, useEffect } from "react";
import RestaurantDataService from "../services/restaurant";
import { Link } from "react-router-dom";
const RestaurantsList = props => {
const [restaurants, setRestaurants] = useState([]);
const [searchName, setSearchName ] = useState("");
const [searchZip, setSearchZip ] = useState("");
const [searchCuisine, setSearchCuisine ] = useState("");
const [cuisines, setCuisines] = useState(["All Cuisines"]);
useEffect(() => {
retrieveRestaurants();
retrieveCuisines();
}, []);
const onChangeSearchName = e => {
const searchName = e.target.value;
setSearchName(searchName);
};
const onChangeSearchZip = e => {
const searchZip = e.target.value;
setSearchZip(searchZip);
};
const onChangeSearchCuisine = e => {
const searchCuisine = e.target.value;
setSearchCuisine(searchCuisine);
};
const retrieveRestaurants = () => {
RestaurantDataService.getAll()
.then(response => {
console.log(response.data);
setRestaurants(response.data.restaurants);
})
.catch(e => {
console.log(e);
});
};
const retrieveCuisines = () => {
RestaurantDataService.getCuisines()
.then(response => {
console.log(response.data);
setCuisines(["All Cuisines"].concat(response.data));
})
.catch(e => {
console.log(e);
});
};
const refreshList = () => {
retrieveRestaurants();
};
const find = (query, by) => {
RestaurantDataService.find(query, by)
.then(response => {
console.log(response.data);
setRestaurants(response.data.restaurants);
})
.catch(e => {
console.log(e);
});
};
const findByName = () => {
find(searchName, "name")
};
const findByZip = () => {
find(searchZip, "zipcode")
};
const findByCuisine = () => {
if (searchCuisine === "All Cuisines") {
refreshList();
} else {
find(searchCuisine, "cuisine")
}
};
return (
<div>
<div className="row pb-1">
<div className="input-group col-lg-4">
<input
type="text"
className="form-control"
placeholder="Search by name"
value={searchName}
onChange={onChangeSearchName}
/>
<div className="input-group-append">
<button
className="btn btn-outline-secondary"
type="button"
onClick={findByName}
>
Search
</button>
</div>
</div>
<div className="input-group col-lg-4">
<input
type="text"
className="form-control"
placeholder="Search by zip"
value={searchZip}
onChange={onChangeSearchZip}
/>
<div className="input-group-append">
<button
className="btn btn-outline-secondary"
type="button"
onClick={findByZip}
>
Search
</button>
</div>
</div>
<div className="input-group col-lg-4">
<select onChange={onChangeSearchCuisine}>
{cuisines.map(cuisine => {
return (
<option value={cuisine}> {cuisine.substr(0, 20)} </option>
)
})}
</select>
<div className="input-group-append">
<button
className="btn btn-outline-secondary"
type="button"
onClick={findByCuisine}
>
Search
</button>
</div>
</div>
</div>
<div className="row">
{restaurants.map((restaurant) => {
const address = `${restaurant.address.building} ${restaurant.address.street}, ${restaurant.address.zipcode}`;
return (
<div className="col-lg-4 pb-1">
<div className="card">
<div className="card-body">
<h5 className="card-title">{restaurant.name}</h5>
<p className="card-text">
<strong>Cuisine: </strong>{restaurant.cuisine}<br/>
<strong>Address: </strong>{address}
</p>
<div className="row">
<Link to={"/restaurants/"+restaurant._id} className="btn btn-primary col-lg-5 mx-1 mb-1">
View Reviews
</Link>
<a target="_blank" href={"https://www.google.com/maps/place/" + address} className="btn btn-primary col-lg-5 mx-1 mb-1">View Map</a>
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
);
};
export default RestaurantsList;
but the problem arise when i click the view review button in the card shown in this page where the screen does not show anything and recieve anything kind of data. the code as follows:
import React, { useState, useEffect } from "react";
import RestaurantDataService from "../services/restaurant";
import { Link } from "react-router-dom";
const Restaurant = props => {
const initialRestaurantState = {
id: null,
name: "",
address: {},
cuisine: "",
reviews: []
};
const [restaurant, setRestaurant] = useState(initialRestaurantState);
const getRestaurant = id => {
RestaurantDataService.get(id)
.then(response => {
setRestaurant(response.data);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
useEffect(() => {
getRestaurant(props.match.params.id);
}, [props.match.params.id]);
const deleteReview = (reviewId, index) => {
RestaurantDataService.deleteReview(reviewId, props.user.id)
.then(response => {
setRestaurant((prevState) => {
prevState.reviews.splice(index, 1)
return({
...prevState
})
})
})
.catch(e => {
console.log(e);
});
};
return (
<div>
{restaurant ? (
<div>
<h5>{restaurant.name}</h5>
<p>
<strong>Cuisine: </strong>{restaurant.cuisine}<br/>
<strong>Address: </strong>{restaurant.address.building} {restaurant.address.street}, {restaurant.address.zipcode}
</p>
<Link to={"/restaurants/" + props.match.params.id + "/review"} className="btn btn-primary">
Add Review
</Link>
<h4> Reviews </h4>
<div className="row">
{restaurant.reviews.length > 0 ? (
restaurant.reviews.map((review, index) => {
return (
<div className="col-lg-4 pb-1" key={index}>
<div className="card">
<div className="card-body">
<p className="card-text">
{review.text}<br/>
<strong>User: </strong>{review.name}<br/>
<strong>Date: </strong>{review.date}
</p>
{props.user && props.user.id === review.user_id &&
<div className="row">
<a onClick={() => deleteReview(review._id, index)} className="btn btn-primary col-lg-5 mx-1 mb-1">Delete</a>
<Link to={{
pathname: "/restaurants/" + props.match.params.id + "/review",
state: {
currentReview: review
}
}} className="btn btn-primary col-lg-5 mx-1 mb-1">Edit</Link>
</div>
}
</div>
</div>
</div>
);
})
) : (
<div className="col-sm-4">
<p>No reviews yet.</p>
</div>
)}
</div>
</div>
) : (
<div>
<br />
<p>No restaurant selected.</p>
</div>
)}
</div>
);
};
export default Restaurant;
please kindly answer the question if possible
when I try to upload an image , i get these 2 errors :
(reader.onloadend is not a function at privewFile) and (Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.)
this is the code :
export default function Register() {
const [user, setUser] = useState({
username:"",
email:"",
password:"",
age:0,
gender:"",
})
const [file, setFile] = useState(null)
const [img,setImg] = useState("")
const handleChange = (event) => {
setUser({
...user,
[event.target.id]: event.target.value,
});
}
function privewFile(file) {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend(() => {
setImg(reader.result)
})
console.log(img);
}
const handleFile = (event) => {
if (event.target.files && event.target.files[0]) {
const pic = event.target.files[0]
setFile(pic)
privewFile(file)
}}
const handleSubmit = (event) => {
event.preventDefault()
console.log(user);
console.log(file);
}
return (
<div className='container'>
<div className='left'>
<div className='logo'>
<DatabaseNetworkPoint theme="outline" size="150" fill="#333"/>
<h1>WonderHit</h1>
</div>
<form className='form' onSubmit={handleSubmit}>
<input placeholder='Username' id='username' value={user.username} className='field' type="text" onChange={handleChange} />
<input placeholder='Email' id='email' value={user.email} className='field' type="email" onChange={handleChange} />
<input placeholder='Password' id='password' value={user.password} className='field' type="password" onChange={handleChange} />
<input placeholder='Age' id='age' value={user.age} className='field' type="number" onChange={handleChange} />
<input placeholder='Gender' id='gender' value={user.gender} className='field' type="text" onChange={handleChange} />
<div className='profilePic'>
<div className='Photo'>
<img className='Photo' src={img} />
</div>
<input className='field2' id='file' type="file" accept=".png, .jpg, .jpeg" onChange={(e) => handleFile(e)} />
<label htmlFor = "file" className='uploadPic' >+</label>
</div>
<button className='submit' type="submit">Register</button>
<h3 className='routing'>You already have an account ? <Link className='rot' to="/">Login</Link></h3>
</form>
</div>
<img className='right' src='https://images.unsplash.com/photo-1562577309-4932fdd64cd1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80' />
</div>
)
}
what is the problem here guys ? can you help ?????
It should be working just fine , I have no idea what is wrong
In your handleFile function. You are creating a constant of pic. You need to send this constant to the priviewFile function I think....like this:
const handleFile = (event) => {
if (event.target.files && event.target.files[0]) {
const pic = event.target.files[0]
setFile(pic)
privewFile(pic)
}}
I am working on a simple CRUD project with the MERN stack.
In the project, I'm trying to update the blog for the particular article. But it's not updating the blogs collection.
index.js
app.put('/updateblog/:id', async (req, res) => {
const newBlogTitle = req.body.newBlogTitle;
const newBlogAuthor = req.body.newBlogAuthor;
const newBlogContent = req.body.newBlogContent;
const {id} = req.params;
console.log(id);
try{
await Blog.findByIdAndUpdate( id , (err , updatedBlog) => {
updatedBlog.blogTitle = newBlogTitle;
updatedBlog.blogAuthor = newBlogAuthor;
updatedBlog.blogContent = newBlogContent;
updatedBlog.save();
res.send("updated");
})
}catch(error){
console.log(error);
}
})
Edit.js
Using aixos to get the post all the post details:
useEffect(() => {
axios.get("http://localhost:5000/blogList" )
.then((response) => {
setContent(response.data)
console.log(response.data)
})
}, [])
Update the data using put method
const log = async(e) => {
e.preventDefault();
if (editorRef.current) {
console.log(editorRef.current.getContent());
//setContent(editorRef.current.getContent());
setNewBlogContent(editorRef.current.getContent())
}
try{
await axios.put('http://localhost:5000/updateblog/' + id, {
newBlogTitle,
newBlogAuthor,
newBlogContent
}).then(response => {
console.log(response.data);
console.log('Blog successfully updated')
navigate('/blog')
}).catch((error) => {
console.log(error)
})
}catch(error){
console.log(error);
}
}
if (!content) return null;
Blog Section
<div className="container">
<div className='fw-bold text-center mt-3 fs-1'>Edit Content</div>
<form onSubmit={log}>
{content.filter(cnt => cnt._id === id )
.map(cDetails => (
<div key={cDetails._id}>
<div className='container'>
<div className='container bg-light mt-3 p-3'>
<label for="Blogtitle" className="form-label mt-3">Blog Title</label>
<input type='text' name="title" id="Blogtitle" className=' mt-3 form-control' required
value={newBlogTitle}
onChange={e => setNewBlogTitle(e.target.value)} placeholder={cDetails.blogTitle} />
<label for="BlogAuthor" className="form-label mt-3">Blog Title</label>
<input type='text' name="authorName" id="BlogAuthor" className=' mt-3 form-control'
value={newBlogAuthor} required
onChange={e => setNewBlogAuthor(e.target.value)} placeholder={cDetails.blogAuthor} />
{/* <div className=' bg-light mt-3 text-muted fst-italic text-end px-4'> - By {cDetails.blogAuthor}</div> */}
</div>
<div className='container mt-5'>
<Editor
onInit={(evt, editor) => {
setNewBlogContent(editor.getContent({format: 'html'}));
}}
initialValue={cDetails.blogContent}
onEditorChange={(newValue, editor) => {
setNewBlogContent(editor.getContent({format: 'html'}));
}}
/>
</div>
</div>
</div>
) )
}
<button type='submit' className="btn btn-primary mt-3 mx-4" >Update editor content</button>
</form>
</div>
</div>
The content state example output,
I am trying to create a to-do list app with a timestamp and strike-through the list item when the delete button is clicked, but when I click the delete button all the items get stricked-through.
I have looked everywhere but I cant get it to work for my code. I am able to extract unique id through delete button function but i cant understand how to use that id to strike only that id.
import "../App.css";
import moment from "moment";
const List = () => {
const [strike, setStrike] = useState(false);
const [addtime, setaddTime] = useState(moment().utcOffset("+05:30").format("YYYY-MM-DD HH:mm:ss ").toString());
const [store, setStore] = useState([]);
const [endTime, setendTime] = useState();
const [inputData, setInputData] = useState('');
const [items, setItems] = useState([]);
//to add an item
const addItem = () => {
if (!inputData) {
} else {
const allInputData = {id: new Date().getTime().toString(), name:inputData}
setItems([...items, allInputData]);
setInputData("");
setaddTime(
moment().utcOffset("+05:30").format("YYYY-MM-DD HH:mm:ss ").toString()
);
setStore([...store, addtime]);
}
};
// to delete an item
const deleteItem = (index) => {
const boolstrike = items.filter((elem) => {
return index == elem.id;
})
console.log(boolstrike);
setStrike(!!boolstrike);
};
//to remove time
const deleteTime = () => {
setendTime (moment().utcOffset("+05:30").format("YYYY-MM-DD HH:mm:ss ").toString());
}
// to remove all items
const removeAll = () => {
setItems([]);
setStore([]);
};
return (
<>
<div className="parent-div">
<div className="child-div">
<h3>TO DO LIST</h3>
<div className="addItems">
<input
type="text"
placeholder="what needs to be done?"
value={inputData}
onChange={(e) => setInputData(e.target.value)}
/>
<button
type="button"
onClick={addItem}
className="btn btn-secondary"
>
Create
</button>
</div>
<div id="wrapper">
<div id="left" className="showItems">
{items.map((elem) => {
return (
<div className="eachItem" key={elem.id}>
<h3
style={{
textDecoration: strike ? "line-through" : "none",
}}
>
{elem.name}
</h3>
<button
type="button"
onClick={() => deleteItem(elem.id)}
className="btn btn-danger btn-sm"
>
Delete
</button>
</div>
);
})}
</div>
<div id="right">
{store.map((elim, ind) => {
return (
<div className="eachdate" key={ind}>
<h6>{"Task Created at:" + elim} </h6>
<button
type="button"
onClick={() => deleteTime()}
className="btn btn-danger btn-sm"
>
Delete
</button>
</div>
);
})}
</div>
</div>
<div className="showItems">
<button onClick={removeAll} className="btn btn-danger">
Delete All
</button>
</div>
</div>
</div>
</>
);
};
export default List;```
You can try to add strike in the items obj and track that. in that way, if delete btn is clicked, you can mark that item as strikedout.
You can set strike while delete
const deleteItem = (index) => {
const updatedItems = items.filter((elem) => {
if (index == elem.id) {
elem.strike = true;
}
return elem;
});
setItems(updatedItems);
};
and based on this property class will be applied, only deleted items will strick out.
updated code:
import React, { useState } from 'react';
import './App.css';
import moment from 'moment';
const List = () => {
const [strike, setStrike] = useState(false);
const [addtime, setaddTime] = useState(
moment().utcOffset('+05:30').format('YYYY-MM-DD HH:mm:ss ').toString()
);
const [store, setStore] = useState([]);
const [endTime, setendTime] = useState();
const [inputData, setInputData] = useState('');
const [items, setItems] = useState([]);
//to add an item
const addItem = () => {
if (!inputData) {
} else {
const allInputData = {
id: new Date().getTime().toString(),
name: inputData,
};
setItems([...items, allInputData]);
setInputData('');
setaddTime(
moment().utcOffset('+05:30').format('YYYY-MM-DD HH:mm:ss ').toString()
);
setStore([...store, addtime]);
}
};
// to delete an item
const deleteItem = (index) => {
const updatedItems = items.filter((elem) => {
if (index == elem.id) {
elem.strike = true;
}
return elem;
});
setItems(updatedItems);
};
//to remove time
const deleteTime = () => {
setendTime(
moment().utcOffset('+05:30').format('YYYY-MM-DD HH:mm:ss ').toString()
);
};
// to remove all items
const removeAll = () => {
setItems([]);
setStore([]);
};
return (
<>
<div className="parent-div">
<div className="child-div">
<h3>TO DO LIST</h3>
<div className="addItems">
<input
type="text"
placeholder="what needs to be done?"
value={inputData}
onChange={(e) => setInputData(e.target.value)}
/>
<button
type="button"
onClick={addItem}
className="btn btn-secondary"
>
Create
</button>
</div>
<div id="wrapper">
<div id="left" className="showItems">
{items.map((elem) => {
console.log(elem);
return (
<div className="eachItem" key={elem.id}>
<h3
style={{
textDecoration: elem.strike ? 'line-through' : 'none',
}}
>
{elem.name}
</h3>
<button
type="button"
onClick={() => deleteItem(elem.id)}
className="btn btn-danger btn-sm"
>
Delete
</button>
</div>
);
})}
</div>
<div id="right">
{store.map((elim, ind) => {
return (
<div className="eachdate" key={ind}>
<h6>{'Task Created at:' + elim} </h6>
<button
type="button"
onClick={() => deleteTime()}
className="btn btn-danger btn-sm"
>
Delete
</button>
</div>
);
})}
</div>
</div>
<div className="showItems">
<button onClick={removeAll} className="btn btn-danger">
Delete All
</button>
</div>
</div>
</div>
</>
);
};
export default List;
II am trying to do a post request to the database to post an object called questions using "react-dom": "^15.6.1". The data might be something as follows:
{description: 'What is E-commerce?', ismeeting: false, expID: '123A2'}
What i am trying to do is take the "description" , "ismeeting" and ,"expID" values from a form and a checkbox (checkbox for "ismeeting") in the front end and pass it to the backend. To get the description value for instance; i am using this.refs.description.value. However i am getting an error Using this.refs is deprecated in the onSubmit(e) function and Using string literals in ref attributes is deprecated react/no-string-refs in the render() function
Here is the OnSubmit code.
onSubmit(e) {
const newQues = {
description: this.refs.description.value,
ismeeting: this.refs.check_me.checked,
expID: this.refs.expID.value
};
this.addQues(newQues);
e.preventDefault();
}
and here is the render() code.
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input type="text" name="description" ref="description"/>
<label htmlFor="description"> Description </label>
</div>
<div className="input-field">
<input type="text" name="expID" ref="expID"/>
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="ismeeting" ref="check_me" />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
finally this is the full code.
import React, { Component } from 'react';
import axios from 'axios';
import '../Styles.scss';
class Questions extends Component {
addQues(newQues) {
console.log(newQues);
axios.request({
method: 'Post',
url: 'http://localhost:3001/api/Questions',
data: newQues
}).then(response => {
}).catch(err => console.log(err));
}
constructor() {
super();
this.state = {
Questions: []
};
}
onSubmit(e) {
const newQues = {
description: this.refs.description.value,
ismeeting: this.refs.check_me.checked,
expID: this.refs.expID.value
};
this.addQues(newQues);
e.preventDefault();
}
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input type="text" name="description" ref="description"/>
<label htmlFor="description"> Description </label>
</div>
<div className="input-field">
<input type="text" name="expID" ref="expID"/>
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="ismeeting" ref="check_me" />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
}
export default Questions;
String refs have been deprecated. So what you need to do is update your refs
<input type="text" name="expID" ref="expID"/>
should be updated to
setExpIdRef = (r) => this.expIdRef = r;
onSubmit = (e) => {
const newQues = {
expID: this.expIdRef.value
};
// Do what you need to with newQuest i.e call your database
}
render() {
...
<input type="text" name="expID" ref={this.setExpIdRef}/>
}
The best solution is to make your inputs controlled inputs. Where you keep track of the value in the state.
constructor() {
super();
this.state = {
expID: ''
};
}
onExpIdChange = (e) => {
this.setState({
expID: e.target.value
})
}
onSubmit = (e) => {
const newQues = {
expID: this.state.expID
};
// Do what you need with the newQues object
}
render() {
...
<input type="text" name="expID" onChange={this.onExpIdChange} />
}