Reputation: 854
I am creating a simple react app for my learning. So I am kind of beginner in react. I am facing one problem that, it is not updating my input field value whenever I am typing something. It keeps as it is whatever are coming from api.
Here is my code.
import React, { useState, useContext, useEffect } from 'react';
import axios from 'axios';
export default function Edit(id) {
const [ name, setName] = useState([]);
const [ email, setEmail] = useState([]);
useEffect( () => {
const singleData = async () => {
try{
let response = await axios.get( 'http://localhost:8000/api/show/' + id.match.params.id)
.then(res => {
setName(res.data.name);
setEmail(res.data.email);
})
.catch((error) => {
console.log(error);
})
}
catch(error) {
console.log(error)
}
}
singleData()
})
return (
<div>
<form>
<div className="form-group">
<input type="text" value={name} onChange={(e) => setName(e.target.value)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
</div>
<div className="form-group">
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="form-control" id="exampleInputPassword1" placeholder="Password" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
);
}
Upvotes: 2
Views: 674
Reputation: 11760
useEffect with no dependencies array will run on every re-render, to run the effect only once when the component mounts add an empty dependencies array
useEffect(() => {
const singleData = async () => {
try {
const { data } = await axios(
`http://localhost:8000/api/show/${id.match.params.id}`,
)
setName(data.name)
setEmail(data.email)
} catch (error) {
console.log(error)
}
}
singleData()
}, [])
Upvotes: 2
Reputation: 2422
Without an array dependency, the useEffect
runs every time the state is updated. So it effectively just undoes whatever you type and replaces it with another fetch.
Assuming you only want it to fetch when the component mounts, add an empty dependency array to your useEffect
i.e.
useEffect( () => {
const singleData = async () => {
try{
let response = await axios.get( 'http://localhost:8000/api/show/' + id.match.params.id)
.then(res => {
setName(res.data.name);
setEmail(res.data.email);
})
.catch((error) => {
console.log(error);
})
}
catch(error) {
console.log(error)
}
}
singleData()
},[])
Upvotes: 1