Search code examples
reactjsreact-nativereact-cache

React: Cannot ready property 'readContext' of undefined


react-cache is not working with Suspense.

My code

  import React, { Suspense } from "react";
  import ReactDOM from "react-dom";
  import { unstable_createResource as createResource } from "react-cache";

    const MarkdownCache = createResource(input => {
       return new Promise(resolve => resolve(input));
    });

    const App = () => {
        return (
           <Suspense fallback={<div>Loading...</div>}>
               <Test />
           </Suspense>
        );
    }

    const Test = () => {
           const input = MarkdownCache.read("Test react cache");
           return input;
     }

const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

Versions I am using:

  react: 16.8.0-alpha.0
  react-dom: 16.8.0-alpha.0
  react-cache: 2.0.0-alpha.1

Solution

  • The workaround for this problem I found from the internet is...

    If you just want to run the program in the development env, you can modify the code in 'react-cache/cjs/react-cache.development.js' by yourself: old:

        var currentOwner = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
    
        function readContext(Context, observedBits) {
            var dispatcher = currentOwner.currentDispatcher;
            if (dispatcher === null) {
            throw new Error('react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.');
           }
           return dispatcher.readContext(Context, observedBits);
         }
    

    'currentOwner' is no use except in function readContext. so here is the new:

          var currentDispatcher =      React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;
    
         function readContext(Context, observedBits) {
              var dispatcher = currentDispatcher.current;
              if (dispatcher === null) {
                   throw new Error('react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.');
               }
              return dispatcher.readContext(Context, observedBits);
             }
    

    And that work in my code.