preactjs/preset-vite

React Router 6.x/5.x: TypeError: Cannot read properties of undefined (reading 'context')

rhengles opened this issue · 1 comments

Related issue: remix-run/react-router#10172

What version of React Router are you using?

6.8.2 (latest)

Steps to Reproduce

I started with Vite and @preact/preset-vite.
I want my project to be fully compatible with React, but using @preact/compat.

Expected Behavior

The router works in the server and the browser, including the useLocation() and useNavigate() hooks.

Actual Behavior

When I start the app, I get this error:

TypeError: Cannot read properties of undefined (reading 'context')
    at Object.exports.useContext (/project/home/rhengles/workspace/node_modules/preact/hooks/dist/hooks.js:1:2680)
    at Object.Routes (/project/home/rhengles/workspace/node_modules/react-router/dist/umd/react-router.development.js:1177:46)
    at file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:6332
    at F (file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:6359)
    at F (file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:6434)
    at F (file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:6434)
    at F (file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:6434)
    at F (file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:7454)
    at Proxy.S (file:///project/home/rhengles/workspace/node_modules/preact-render-to-string/dist/index.mjs:1:4833)
    at render (entry-server.jsx:8:4)
    at file:///project/home/rhengles/workspace/server.js:76:23

Link to CodeSandbox

I've managed to get it almost working with react-router-dom@5.x if I don't try to use any of the router hooks.
If I get the useLocation() or useHistory() hooks from 5.x, I get exactly the same error as above as react-router-dom@6.x.

The error is happening on this line:

https://github.com/preactjs/preact/blob/master/hooks/src/index.js#L319

export function useContext(context) {
	const provider = currentComponent.context[context._id];
	//               ^^^^^^^^^^^^^^^^
	// currentComponent is undefined

I think I found the problem in React Router, below is the link of my PR with the fix:

remix-run/react-router#10175