Set state before routing to other path

Viewed 234

I am using react router to navigate between different pages. Everytime I navigate to another page the state must be updated based on the new path. I use a context to provide this state for all components. My code looks like this:

export const App = () => {
  return (
    <MyContextProvider>
      <Router>
        <Switch>
          <Route path="/path1" render={(props) => {
            const mode = props.match.path.replace('/', '')
            return <DataImportWrapper mode={mode} />
          }
          }/>
        </Switch>
      </Router>
    </MyContextProvider>
  )
}

const DataImportWrapper = ({mode}) => {
  const { setMode } = useContext(MyContext)
  setMode(mode)
  return <DataImport />
}

It is very important that the state is updated BEFORE rendering any components of another route because all subcomponents are using that state. With this code I get the warning: Cannot update a component ('MyContextProvider') while rendering a different component ('DataImportWrapper'). and also my state is not updated. Does anyone know what I am doing wrong?

1 Answers

What I would suggest is to set the mode in the Contextprovider and move the Contextprovider within the router. This way you don't need to create an extra wrapper and the mode is always set before rendering other components. You can the set the mode in your ContextProvider

const MyContextProvider = ({ children }) => {
  const { path } = useRouteMatch("/path1");

  return (
    <MyContext.Provider value={{ mode: path.replace('/', '') }}>
      {children}
    </MyContext.Provider>
  )
}


export const App = () => {
  return (
      <Router>
        <Switch>
          <MyContextProvider>
            <Route path="/path1" ><DataImport /></Route>
          </MyContextProvider>
        </Switch>
      </Router>
  )
}

Related