Search code examples
react-nativereduxexporeferenceerror

ReactNative Expo Redux ReferenceError: Can't find variable: document


expo: 3.27.4 => 4.1.3

react-native-cli: 2.0.1

react-native: 0.62.2 => 0.63.4

@reduxjs/toolkit: 1.5.0

react-redux: 7.2.2

redux: 4.0.5

I'm new to react-native and am trying to implement Redux into my Expo app. This code builds multiple times (I assume this is because of the expo registerRootComponent(App)) and then once it runs I get a:

"ReferenceError: Can't find variable: document"

My index.js where the error occurs currently looks like this:

    import { registerRootComponent } from 'expo';

    import App from './App'
    import React from 'react'
    import ReactDOM from 'react-dom'
    import store from './app/store'
    import { Provider } from 'react-redux'


    ReactDOM.render(
        <Provider store={store}>
          <App />
        </Provider>,
    document.getElementById('root')
    )

    registerRootComponent(App);

I've also tried putting into it's own function in, because I've had a similar error where this helped.

function App () {
    return (
        ReactDOM.render(
          <Provider store={store}>
              <MainFunc />
          </Provider>,
          document.getElementById('root')
        )
    )
}

But once again it cannot find document. Please, help me find document.


Solution

  • Not a perfect solution.

    I wasn't able to make the ReactDOM.render part work, but using hooks seems to do the job of re-rendering my components fine.

    Step 1

    Remove the RectDOM.render from index.js and replace with standard expo:

    import { registerRootComponent } from 'expo';
    
    import App from './App';
    
    registerRootComponent(App);
    

    Step 2

    Surround you App() content with Provider (don't forget to import Provider and store):

    import store from './app/store';
    import { Provider } from "react-redux";
    
    function App () {
      return (
        <Provider store={store}>
          <Components/>
        </Provider>
      )
    }
    

    Step 3

    In the component you want to reload when a change occurs in redux memory create an instance of your object:

      const currentTicket = useSelector((state) =>
        state.tickets.find((ticket) => ticket.id == global.currentTicketID)
      );
    

    Note: My redux store is an array of ticket objects so I must find the ticket I want to work with using the array find function

    And then create a hook that takes in a value of your instance:

      useEffect(() => {
        //code you want to run on change of the instance value
      }, [currentTicket.num]);
    

    Note: this only works if you have functional components (not classes)