ReactJS: Pass object into fetch promise

Viewed 167

I'm kind of new react, and this quill plugin is really confusing me. I'm using react-quilljs to display an editable rich text field, which is supposed to be pre-populated with a value retrieved using fetch from my API. Seems pretty simple, right? But I'm getting the error 'quill is undefined' in the fetch callback.

import React, { useState, useEffect } from "react";

import { useQuill } from "react-quilljs";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// see https://www.npmjs.com/package/react-quilljs

export default function View(props) {
  
  const [group, setGroup] = useState([]);
  const { quill, quillRef } = useQuill({});

  useEffect(() => {

      fetch('/api/groups/' + props.id , {
                method: 'GET'
            })
            .then(res => res.json())
            .then((data) => {
                
                setGroup(data);

                quill.setContents(JSON.parse(data));                
            })
            .catch(console.log);

    }, [quill]);

    return(
        
        <div >
            <div id="descriptionInput" ref={quillRef} />
        </div>
    );
}

Of course I've omitted a lot of the code, but I think it should be enough to illustrate the problem. I think, basically the question is, how do I pass the quill object into the fetch promise?

I have searched for the answer but for some reason can't find anything on this.

2 Answers

After some more inspection, it turns out useEffect is being called multiple times, and quill is not available right away (as Asher Lim notes). So adding a check if (quill) inside the fetch promise solves the problem.

Of course this means that the fetch is being done more times than necessary, which can be solved with some more refactoring.

Related