0

I have a simple page editor, When a user clicks edit page it opens an editor. I am passing the ID of the page using redux which will be used to get data from API.

Here is my Editor.

const [pageData, setPageData] = useState("");

  const getPage = async (id) => {
    try {
      const response = await api.get(`/landing_pages/${id}`);
      console.log("page", response.data); // displays data at the end
      setPageData(response.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {

    getPage(pageID);

    console.log('Page Data', pageData) // displays nothing

    let LandingPage = pageData;

     const editor = grapesjs.init({
       container: "#editor",
       components: LandingPage.components || LandingPage.html,
     })

  }, [pageID, getPage])

Why is Page Data display nothing even though the data from API is returned and is displayed in the console at the end? what am I doing wrong here?

The Dead Man
  • 6,258
  • 28
  • 111
  • 193

1 Answers1

1

Even if you await your getPage call, the updated pageData won't be available until the next render cycle so your assignment to LandingPage will be one cycle behind.

You should instead update in one useEffect and watch for changes to pageData in another.

const [pageData, setPageData] = useState("");

  useEffect(() => {
    const getPage = async (id) => {
      try {
        const response = await api.get(`/landing_pages/${id}`);
        console.log("page", response.data); // displays data at the end
        setPageData(response.data);
      } catch (error) {
        console.log(error);
      }
    };

    getPage(pageID);
  }, [pageID]);

  useEffect(() => {
    console.log('Page Data', pageData); // displays updated pageData

    let LandingPage = pageData;

    const editor = grapesjs.init({
      container: "#editor",
      components: LandingPage.components || LandingPage.html,
    });
  }, [pageData]);
pilchard
  • 12,414
  • 5
  • 11
  • 23