I'm working with react-quilljs See the docs where it goes into setting up "With Initial Value." Using their docs this works fine until you try to pull an initial value from a database using useEffect. I continuously get the error TypeError: Cannot read properties of undefined (reading 'length') from this line of code below:
quill.clipboard.dangerouslyPasteHTML(savedIntroText);
Any idea how to correctly go about this?
const [savedIntroText, setSavedIntroText] = useState();
// Getting text in from database
useEffect(() => {
const fetchResults = async () => {
const result = await axios({
method: "GET",
url: "http://localhost:4000/userData",
withCredentials: true,
});
setSavedIntroText(result.data.introEssayText);
};
fetchResults();
}, []);
//Setting initial Quill value here, as shown in docs:
if (quill) {
quill.clipboard.dangerouslyPasteHTML(savedIntroText);
}
const handleUpdatedIntro = () => {
const text = quill.getText();
setSavedIntroText(text);
};
// ===== Implementing Quill ======
<div ref={quillRef} onInput={handleUpdatedIntro} />;
With your current code, quill.clipboard.dangerouslyPasteHTML(savedIntroText);
is called before any value is set for savedIntroText
(thus the undefined error you are seeing). If you would like the value to be pasted once retrieved by the API try moving it into your useEffect
, after the data is loaded, e.g.:
useEffect(() => {
const fetchResults = async () => {
// Only request/load data once quill is loaded
if (!quill) {
return;
}
const result = await axios({
method: "GET",
url: "http://localhost:4000/userData",
withCredentials: true,
});
quill.clipboard.dangerouslyPasteHTML(result.data.introEssayText);
};
fetchResults();
}, [quill]);