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?