• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

147
Vistas
Get data using useeffect hook in react js

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?

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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]);
about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda