I have this api running on my localhost, using drf. I defined a put method to use to update an object. When i do this in the backend it works, everything gets updated, but when i do it in the frontend nothing gets updated but i get a 200 OK status code. How can i make it work?
Here is my react code:
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router';
import axios from 'axios';
const EkoEditPage = () => {
const [disco, setDisco] = useState("")
const [feederSource33kv, setFeederSource33kv] = useState("")
const [injectionSubstation, setInjectioSubstation] = useState("")
const [feederName, setFeederName] = useState("")
const [band, setBand ] = useState("")
const [status, setStatus] = useState("")
const history = useHistory();
const { id } = useParams();
const loadEkoMyto = async () => {
const { data } = await axios.get(`http://127.0.0.1:8000/main/view/${id}`);
setDisco(data.dicso)
setFeederSource33kv(data.feeder_source_33kv)
setInjectioSubstation(data.injection_substation)
setFeederName(data.feeder_name )
setBand(data.band)
setStatus(data.status)
}
const updateEkoMyto = async () => {
let formField = new FormData()
formField.append('disco', disco)
formField.append('feeder_source_33kv', feederSource33kv)
formField.append('injecttion_substation', injectionSubstation)
formField.append('feeder_name',feederName)
formField.append('band', band)
formField.append('status', status)
await axios({
method: 'PUT',
url: `http://127.0.0.1:8000/main/edit/${id}`,
data: formField
}).then(response => {
console.log(response.data)
})
}
useEffect (() => {
loadEkoMyto()
}, [])
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Update A Student</h2>
<div className="form-group">
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="disco"
value={disco}
onChange={(e) => setDisco(e.target.value)}
/>
</div>
<div className="form-group">
<input
className="form-control form-control-lg"
placeholder="Enter Your E-mail Address"
name="feeder_source_33kv"
value={feederSource33kv}
onChange={(e) => setFeederSource33kv(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Phone Number"
name="injection_substation"
value={injectionSubstation}
onChange={(e) => setInjectioSubstation(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your address Name"
name="address"
value={feederName}
onChange={(e) => setFeederName(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="address"
value={band}
onChange={(e) => setBand(e.target.value)}
/>
</div>
<select name="status" onChange={(e) => setStatus(e.target.value)}>
<option value={status}>Yes</option>
<option value={status}>No</option>
</select>
<button className="btn btn-primary btn-block" onClick={updateEkoMyto}>Update Eko</button>
</div>
</div>
);
};
export default EkoEditPage;
}
Related
What I am trying to do is when the user click the edit button, this will send him to a new page where he can modify the info he already entered. The problem I am facing is that the new page is not showing the data previously entered, so that the user can make his changes. Also, the submit button to send those changes is not working. These are the errors I am getting: src\components\RestaurantList.jsx
Line 25:8: React Hook useEffect has a missing dependency: 'setRestaurants'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Line 31:19: 'response' is assigned a value but never used no-unused-vars
src\components\UpdateRestaurant.jsx
Line 9:12: 'restaurants' is assigned a value but never used no-unused-vars
Line 38:8: React Hook useEffect has a missing dependency: 'code'. Either include it or remove the dependency array react-hooks/exhaustive-deps
My code for the component I am working on:
import React, {useState, useContext, useEffect} from 'react';
import { useHistory, useParams } from 'react-router-dom';
import RestaurantFinder from '../apis/RestaurantFinder';
import { RestaurantsContext } from '../context/RestaurantsContext';
const UpdateRestaurant = (props) => {
const {code} = useParams();
const {restaurants} = useContext(RestaurantsContext);
let history = useHistory();
const [name, setName] = useState("");
const [value, setValue] = useState ("");
const [strain, setStrain] = useState ("");
const [weight, setWeight] = useState ("");
const [authors, setAuthors] = useState ("");
const [number, setNumber] = useState ("");
const [page, setPage] = useState ("");
const [date, setDate] = useState ("");
useEffect(() => {
const fetchData = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setName(response.data.data.restaurant.name);
setValue(response.data.data.restaurant.value);
setStrain(response.data.data.restaurant.strain);
setWeight(response.data.data.restaurant.weight);
setAuthors(response.data.data.restaurant.authors);
setNumber(response.data.data.restaurant.number);
setPage(response.data.data.restaurant.page);
setDate(response.data.data.restaurant.date);
};
fetchData();
}, []);
const handleSubmit = async(e) => {
e.preventDefault();
const updatedRestaurant = await RestaurantFinder.put(`/${code}`, {
name,
value,
strain,
weight,
authors,
number,
page,
date,
});
console.log(updatedRestaurant);
history.push("/");
};
return (
<div>
<form action="">
<div className="form-group">
<label htmlFor="name">Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} code="name" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Value">Value</label>
<input value={value} onChange={(e) => setValue(e.target.value)} code="value" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Strain">Strain</label>
<input value={strain} onChange={(e) => setStrain(e.target.value)} code="strain" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Weight">Weight</label>
<input value={weight} onChange={(e) => setWeight(e.target.value)} code="weight" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Author">Author</label>
<input value={authors} onChange={(e) => setAuthors(e.target.value)} code="authors" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Number">Number</label>
<input value={number} onChange={(e) => setNumber(e.target.value)} code="number" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="Page">Page</label>
<input value={page} onChange={(e) => setPage(e.target.value)} code="page" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="date">Date</label>
<input value={date} onChange={(e) => setDate(e.target.value)} code="date" className="form-control" type="number" />
</div>
<button onClick={handleSubmit} type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
export default UpdateRestaurant
for reusable code, it may be best to just do something like this.
This is probably not the answer, but I hope it helps you find out the answer.
const [data, setData ] = useState({restraunt.loaded:"false"});
useEffect(() => {
const fetch = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setData({...response.data.data, restraunt.loaded:"true"});
};
fetch();
},[Data.restraunt.loaded])
const {name, value , page, loaded } = Data.restaurant;
return (
<div><h1>{loaded}</h1>
</div>
)
If it shows loaded as false then you know it is because of the data not loading.
I am using react-redux hooks.I want to dispatch an action after some validations when the form is submitted. But I cannot call usedispatch() hook outside function component. Is there any way I can dispatch an action using usedispatch() ?
My code looks as below:
import React, { Component } from 'react';
import { register } from '../../actions/auth';
import { useDispatch, useSelector } from "react-redux";
let state = {
username: '',
password1: '',
password2: '',
}
const onSubmit = (e) => {
e.preventDefault()
const dispatch = useDispatch();
if (state.password1 === state.password2) {
dispatch(register(state))
}
else {
console.log('Psw did not matched.')
}
}
const onChange = (e) => {
let field_name = e.target.name;
state[field_name] = e.target.value;
}
const Register = () => {
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form encType="multipart/form-data" onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
onChange={onChange}
required/>
</div>
<div className="form-group">
<label> Password</label>
<input
type="password"
className="form-control"
name="password1"
onChange={onChange}
required/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
onChange={onChange}
required/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
);
}
export default Register;
I get an error that React Hooks cannot be used outside function component and it is obvious. I am looking for a way to dispatch register action after doing some validation when form is submitted.
Since you are writing a React component, it would make sense if you define your state within and other functions within the component. This way you would be able to use hook, useDispatch as well. Also you can make your input fields controlled instead of letting them be uncontrolled
import React, { Component } from 'react';
import { register } from '../../actions/auth';
import { useDispatch, useSelector } from "react-redux";
const Register = () => {
const [state, setState] = useState({
username: '',
password1: '',
password2: '',
});
const onChange = (e) => {
let field_name = e.target.name;
let field_value = e.target.value;
setState(prev => ({...prev, [field_name]: field_value});
}
const dispatch = useDispatch();
const onSubmit = (e) => {
e.preventDefault()
if (state.password1 === state.password2) {
dispatch(register(state))
}
else {
console.log('Psw did not matched.')
}
}
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form encType="multipart/form-data" onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
value={state.username}
onChange={onChange}
required/>
</div>
<div className="form-group">
<label> Password</label>
<input
type="password"
className="form-control"
name="password1"
value={state.password1}
onChange={onChange}
required/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
value={state.password2}
onChange={onChange}
required/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
);
}
export default Register;
I am working on a React project, First I have to Signup then I stored Signup details in local storage so when I came to login screen after entering email and password and when I click submit button then it has to check the email and password from local storage. So if both are same then it should redirects to another page, I am trying to do this but it is showing some error so someone please help me to resolve this error
This is my code
This is Signup.js
import React, { useState, useRef } from 'react';
import './Signup.css';
const Signup = () => {
const [data, sendData] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
sendData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
localStorage.setItem('userInfo', JSON.stringify(data))
}
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='registerForm'>
<form onSubmit={handleSubmit} ref={myForm}>
<div className="form-group mb-2">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" onChange={handleChange} name='firstname' id="firstname" placeholder="Enter firstname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" onChange={handleChange} name='lastname' id="lastname" placeholder="Enter lastname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="email" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="password" placeholder="Enter password"></input>
</div>
<button onClick={resetForm} type="submit" className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Signup
This is Login.js
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import './Login.css';
const Login = () => {
let history = useHistory();
if (login.email && login.password === signupCredentials.email && signupCredentials.password) {
var redirect = () => {
history.push('/dashboard')
}
}
const [login, setLogin] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, login, { [name]: value })
setLogin(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(login)
}
const signupCredentials = JSON.parse(localStorage.getItem('userInfo'))
console.log(signupCredentials.email && signupCredentials.password)
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group mb-2">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="exampleInputEmail1" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="exampleInputPassword1">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="exampleInputPassword1" placeholder="Password"></input>
</div>
<button type="submit" onClick={redirect} className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default Login
If you have any questions please let me know
I am working on a React project In my project I have a scenario to store object in Cookie.
This is my code Login.js
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(data)
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
When I click submit button data will print in console. I have to store that in cookie
So what is the best way to store data object in Cookie
You can save the cookie in document.cookie. But you need to save the data as a string.
You could parse the whole object with JSON.parse, or the more elegant way is to use the specific attributes.
Cookies
But be aware that it is not save to store passwords in cookies.
Try this:
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
document.cookie = `email=${data.email}`;
document.cookie = `username=${data.username}`;
document.cookie = `password=${data.password}`;
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
You just set data to cookie:
document.cookie =
of you can use some npm lib like this:
https://www.npmjs.com/package/react-cookie
I am working on a React project, In my project I have a form, In that form I fetch data by Id
From the backend, Now I am trying to do put method. But I have no idea how doing it so please me
How to send edited data to backend using the put method.
This is my code Editstudentdetails.js
import React, { useState, useEffect } from 'react';
import './Editstudentdetails.css';
import axios from 'axios';
import { withRouter } from 'react-router-dom'
function Editstudentdetails(props) {
const [getStudentDataById, setStudentDataById] = useState([])
const [editStudentDataById, latestEdit] = useState({ name:'', position: '', location: '', salary: '', email: '', password: '' })
const id = props.match.params.id
console.log(id)
useEffect(() => {
const getDataById = async () => {
try {
const result = await axios.get(`http://localhost:7500/api/registration/${id}`)
setStudentDataById(result.data)
console.log(result.data)
} catch (error) {
console.log(error)
}
}
getDataById()
}, [])
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, getStudentDataById, { [name]: value });
setStudentDataById(newData);
const latestData = Object.assign({}, editStudentDataById, { [name]: value })
latestEdit(latestData)
}
const handleSubmit = async e => {
e.preventDefault();
console.warn(editStudentDataById)
const editDataById = async () => {
try {
const response = await axios.put(`http://http://localhost:7500/api/registration/${id}`, editStudentDataById)
latestEdit(response.data)
console.warn(response.data)
} catch (error) {
console.warn(error)
}
}
editDataById()
}
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" name='name' value={getStudentDataById.name} onChange={handleChange} className="form-control" id="name"></input>
</div>
<div className="form-group">
<label htmlFor="position">Position</label>
<input type="text" name='position' value={getStudentDataById.position} onChange={handleChange} className="form-control" id="position"></input>
</div>
<div className="form-group">
<label htmlFor="location">Location</label>
<input type="text" name='location' value={getStudentDataById.location} onChange={handleChange} className="form-control" id="location"></input>
</div>
<div className="form-group">
<label htmlFor="salary">Salary</label>
<input type="number" name='salary' value={getStudentDataById.salary} onChange={handleChange} className="form-control" id="salary"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" name='email' onChange={handleChange} value={getStudentDataById.email} className="form-control" id="email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" name='password' onChange={handleChange} value={getStudentDataById.password} className="form-control" id="password"></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default withRouter(Editstudentdetails)
If you feel I am not clear with my doubt please put a comment Thank you
Please follow this example. It works perfectly.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function EditStudentDetails() {
const [post, setPost] = useState({});
const id = 1;
const handleChange = ({target}) => {
const {name, value} = target;
setPost({...post, [name]: value});
console.log(post);
};
const handleSubmit = async e => {
e.preventDefault();
const editDataById = async () => {
try {
const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
id: id,
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
editDataById();
};
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Title</label>
<input type="text" name='title' value={post.title} onChange={handleChange}
className="form-control" id="title"/>
</div>
<div className="form-group">
<label htmlFor="position">Body</label>
<input type="text" name='body' value={post.body}
onChange={handleChange} className="form-control" id="body"/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default EditStudentDetails;