// App.js - WEB
/* eslint-disable no-undef */
import { hot } from 'react-hot-loader/root';
import React, { Component } from "react";
import { View, Platform, Dimensions, Linking, Text } from "react-native";
import { Routes } from "react-router-dom";
import { ModalContainer } from "react-router-modal";
import IdleTimer from "react-idle-timer";
import {
  BroadcastChannel
} from 'broadcast-channel';
import { withRouter } from './utils/withRouterComponent';

const routeMap = {
  ...CommonRouteMap,
};

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      backgroundColor: "#F36414",
      openmodel: false,
      bootboxtext: "",
      modalopenhide: false,
      measure: getMeasure(this.getWidth()),
      workingtime: true,
      userIdle: false,
      maintainanceText: APP.MAINTAINANCE_TIME,
      linearColors: linearColors(),
      isDuplicate: false
    };
    this.handleWindowPerformanceEvents();

    // Store the previous pathname and search strings
    this.currentPathname = null;
    this.currentSearch = null;

    this.workingTime = dayjs(new Date()).format("HH");
  }

  changeBackground = (color) => {
    this.setState({ backgroundColor: color });
  };

  handleLayout = ({ nativeEvent }) => {
    const { width } = nativeEvent.layout;
    const measure = getMeasure(width);
    this.setState(() => ({ measure }));
  };

  getWidth = () => {
    const { width } = Dimensions.get("window");
    return width;
  };
  handleWindowPerformanceEvents = async () => {
    let ExternalFlag;
    if (Platform.OS === "web") {
      ExternalFlag = sessionStorage.getItem("ExternalFlag");
    } else {
      ExternalFlag = await AsyncStorage.getItem("ExternalFlag");
    }
    let parts = window.location.pathname.split("/");
    let path = parts[parts.length - 1];

    if (window.performance) {
          if (
            performance.navigation.type === 0 &&
            !window.location.pathname != "404Page"
          ) {
            localStorage.clear();
          } else if (!window.location.pathname != "404Page") {
            localStorage.clear();
            const pathName = window.location.pathname;
            const domainName = window.location.origin;
            let updatedPath = pathName.substr(0, pathName.lastIndexOf("/"));
            if (paths.includes(updatedPath)) {
              if (ExternalFlag == 'false') {
                window.location.href = `${domainName}${updatedPath}`;
              }
              return;
            } else {
              if (ExternalFlag == 'false') {
                window.location.href = `${window.location.origin}/servicing/index.html`;
              }
            }
          }
    }
  };
  async componentDidMount() {
    const bc = new BroadcastChannel("MY-Project");
    bc.onmessage = (event) => {
      if (event === "newTab") {
        bc.postMessage(`duplicateTab`);
        this.setState({ isDuplicate: false })
      }
      if (event === `duplicateTab`) {
        bc.close()
      }
    };

    bc.postMessage('newTab');
    this.myContext = {
      ...this.myContext,
      isSupported: await this.isSupportedForVKYC(),
    };
    const windowValues = window.location;
    this.navigateOptions();
    if (
      windowValues.pathname.includes("product") &&
      windowValues.search != ""
    ) {
      fetchUrl(windowValues, this.props);
    }
    this.setState({
      workingtime: true,
     });

    this.interval = setInterval(() => this.timer(windowValues), 5000);
    let machine = null;
    if (Platform.OS === 'web') {
      machine = sessionStorage.getItem('machine');
    }
    if (machine) {
      this.setState({ machine: true })
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  timer = (windowValues) => {
    if (
      windowValues.hostname != "localhost" &&
      this.state.workingtime &&
      !(this.workingTime >= 6 && this.workingTime < 23)
    ) {
      this.setState({
        workingtime: true,
      });
      this.interval = setInterval(() => this.timer(windowValues), 5000);
    }
  };

  navigateOptions() {
    const { history } = this.props;
    if (
      window.location.pathname ===
      `${"/" + injectUrlPaths(window.location).path + "/"}`
    ) {
      history.push(`${"/" + injectUrlPaths(window.location).path + ""}`);
    }
  }

  refresh() {
    let clear = [
      "time",
      "product_name",
      "payment_gateway",
      "stopwatch",
      "credit_opted",
      "flow",
      "easyPay",
      "token",
    ];

    clear.forEach((item) => {
      sessionStorage.removeItem(item);
    });
  }

  handleKeyPress = (event) => {
    if (this.state.userIdle && event.keyCode === 9) {
      event.preventDefault();
    }
  };

  closebootbox = () => {
    if (this.state.userIdle) {
      this.refresh();
      window.removeEventListener("keydown", this.handleKeyPress);
      Linking.openURL(window.location.origin);
    } else {
      this.setState({
        openmodel: false,
        modalopenhide: false,
      });
    }
  };

  onIdle = async () => {
    const pathName = window.location.pathname;
      window.addEventListener('keydown', this.handleKeyPress);
      let ExternalFlag = (Platform.OS === "web") ? sessionStorage.getItem("ExternalFlag") : await AsyncStorage.getItem("ExternalFlag");
      const { history } = this.props;
      let newProps = this.props.location.state;
      newProps = { ...newProps, idle: true };
      let redirectPath = "/servicing/index.html";

      let parts = window.location.pathname.split("/");
      let path = parts[parts.length - 1];
        if (ExternalFlag) {
          history.push({
            pathname: '/servicing/redirectHome',
            state: newProps
          });
        } else {
          let machine = null;
          if (Platform.OS === 'web') {
            machine = sessionStorage.getItem('machine');
          }
          if (machine) {
            window.location.href = `http://localhost:9309/SendStatus?CurrentStatus=Timeout`;
          } else {
            history.push({
              pathname: redirectPath,
              state: newProps
            });
          }
    }
  };

  setTimeout = data => {
    if (data.otptimer) {
      this.idleTimer.pause();
    } else {
      this.idleTimer.resume();
    }
  };
  clearStorage = (data) => {
    data.map((item) => {
      sessionStorage.removeItem(item);
    });
  };

  render() {
    const ua = window.navigator.userAgent;
    return (
      !this.state.isDuplicate ?
        <CacheBuster enableCaching>
          {({ loading, isLatestVersion, refreshCacheAndReload }) => {
            if (loading) return null;
            if (!loading && !isLatestVersion) {
              refreshCacheAndReload();
            }
            return (
              browserSupport(ua) && (
                <LinearGradient {...this.state.linearColors}>
                  <IdleTimer
                    ref={(ref) => {
                      this.idleTimer = ref;
                    }}
                    element={document}
                    onIdle={this.onIdle}
                    debounce={APP.DEBOUNCE}
                    timeout={APP.IDLE_TIMEOUT}
                  />
                  
                  <View onLayout={this.handleLayout} style={styles.container}>
                    <script>
                      window.onpopstate = function() {this.props.history.go(1)};
                    </script>
                    {this.state.workingtime ? (
                      <AppProvider value={{ ...this.myContext, ...this.state }}>
                        <View style={styles.rootStyle}>
                          <CustomBootbox
                            {...this.props}
                            measure={this.state.measure}
                            bootboxtext={this.state.bootboxtext}
                            bootboxmodal={this.state.openmodel}
                            closebootbox={this.closebootbox}
                            hideBlackout
                          />
                          <Routes>
                            {WebRoutesGenerator(
                              { routeMap },
                              this.changeBackground
                            )}
                          </Routes>
                          <ModalContainer />
                        </View>
                      </AppProvider>
                    ) : (
                      <AvailableTimeError
                        maintainanceText={this.state.maintainanceText}
                      />
                    )}
                  </View>
                </LinearGradient>
              )
            );
          }}
        </CacheBuster> : <View style={{ height: Dimensions.get("window").height, }}>
          <View >
            <Text>Previous session is already open...!</Text>
            <Text><br></br> Please close the window and try again </Text>
          </View>
        </View>
    );
  }
}
export default hot((withRouter((App))))

I have a react native project and it was running in the older version of React, React Dom and rest. After updating the application to match the latest version, I am getting the above error and I couldn't find a proper solution for it.

Initially I searched withRouter imports and uses, and then created a custom hook of withRouter. Still the error persists.

import {
    useLocation,
    useNavigate,
    useParams
  } from "react-router-dom";
  
 export function withRouter(Component) {
    function ComponentWithRouterProp(props) {
      let location = useLocation();
      let navigate = useNavigate();
      let params = useParams();
      return (
        <Component
          {...props}
          router={{ location, navigate, params }}
        />
      );
    }
  
    return ComponentWithRouterProp;
  }
1

There are 1 best solutions below

1
Rayan On

This issue is likely surfacing as you might be using --legacy-peer-deps flag when installing node_modules. Now Remove node_modules, and just try to fix code after doing npm install. have a nice day.