Skip to content

setPageData on page.js will never fill pageData state #5

@Yuant-tobing

Description

@Yuant-tobing
    if (!staticContext) {
      useEffect(() => {
        if (!initData) {
          fetch(`data${location.pathname}`)
            .then(r => r.json())
            .then(**setPageData**);
        }
      }, [location]);
    }

maybe, we can use syntax like below:

    if (!staticContext) {
      useEffect(() => {
        if (!initData) {
            let fetchData = async() => {
                let response = fetch(`data${location.pathname}`);
                return await response.json();
            }
            
            fetchData.then((response) => setPageData(response));
        }
      }, [location]);
    }

or maybe, like below

import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

const page = (WrappedComponent) =>
  ({ staticContext }) => {
    const location = useLocation();
    const [pageData, setPageData] = useState(null);

    useEffect(() => {
      let initData = null;

      if (staticContext) {
        initData = staticContext.data;
      }
      
       if (window.__ROUTE_DATA__) {
          initData = window.__ROUTE_DATA__;
       }

      if (!initData) {
        fetch(`data${location.pathname}`)
          .then(async (response) => await response.json())
          .then((response) => initData = response);
      }
      
      setPageData(initData);
      
      return () => {
        if (window.__ROUTE_DATA__) {
          delete window.__ROUTE_DATA__;
        }
      }
    }, [staticContext, location]);

    return (
      pageData && <WrappedComponent pageData={pageData}></WrappedComponent>
    );
  };

export default page;

Thanks, sorry for my bad english

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions