Currently following a slightly older tutorial, but learning using React 18 -- trying to update the text area
in a notes app
It looks like when I type, a character appears and then immediately is deleted automatically
Can anyone confirm if I might be missing a detail here?
for reference if familiar with the project at time 1:37:03 : https://www.youtube.com/watch?v=6fM3ueN9nYM&t=377s
import React, {useState, useEffect} from 'react'
import notes from '../assets/data'
import { useParams } from 'react-router-dom';
import { Link } from 'react-router-dom'
import { ReactComponent as ArrowLeft } from '../assets/arrow-left.svg'
const NotePage = ( history ) => {
const {id} = useParams();
// let note = notes.find(note => note.id===Number(id))
// console.log(id)
let [note, setNote] = useState(null)
useEffect(() => {
getNote()
}, [{id}])
let getNote = async () => {
let response = await fetch(`http://localhost:8000/notes/${id}`)
let data = await response.json()
setNote(data)
}
// let updateNote = async () => {
// await fetch(`http://localhost:8000/notes/${id}`, {
// method: 'PUT',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({...note, 'updated':new Date()})
// })
// }
// let handleSubmit = () => {
// updateNote()
// history.push('/')
// }
return (
<div className="note">
<div className="note-header">
<h3>
<Link to="/">
<ArrowLeft /*onClick={handleSubmit}*/ />
</Link>
</h3>
</div>
<textarea onChange={(e) => {
setNote({...note, 'body': e.target.value}) }}
value={note?.body}>
</textarea>
</div>
)
}
export default NotePage
CodePudding user response:
It looks like the issue might be caused by the fact that the note object is null initially, and the textarea element is trying to access the body property of null.
One way to fix this would be to check if note is truthy before trying to access its properties, like this:
<textarea
onChange={(e) => {
if (note) {
setNote({ ...note, 'body': e.target.value });
}
}}
value={note ? note.body : ''}
>
</textarea>
This way, if note is null, the textarea element will have an empty string as its value.
Another issue I noticed is that you are using the getNote function in the useEffect hook's dependencies array. This is incorrect, because functions are not valid dependencies. Instead, you should just call the function inside the body of the useEffect hook, like this:
useEffect(() => {
getNote();
}, []);
This will make the getNote function run only once, when the component is first rendered.