DEV Community

Idris
Idris

Posted on

Changing input value after populating it with data in react.js

Have you ever faced this problem, when you're trying to edit an input value after populating it with data you get from a server but the input is not responding?

Let's take this scenario:
Let's say you're building a blog and want to edit something after posting it on your blog site, after creating your edit-blog page. You fetch data and then populate the input with the data, but when you click on the input to change its value, the input does not respond.

The solution:

//Declare your states
const [author,setAuthor] = useState('')
const [data,setData] = useState('')

// fetch the data with use effect
useEffect(() =>{
const fetch = async () =>{
const res = await fetch('http://yourUrl.com')
const data = await res.json()
setData(data)
}}
fetch()
},[data])

// use another useEffect hook to set the input value
// using setTimeout 
useEffect(() =>{
setTimeout(()=>{
setAuthor(data.author)
.... // rest of the states, if you have more
}, 1000}
},[author]) //Don't forget to set the dependency array

Enter fullscreen mode Exit fullscreen mode

your input

<input
type='text'
value={author}
>
Enter fullscreen mode Exit fullscreen mode

Done you fix it.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more