How to redirect in React without resetting Redux Store?

Viewed 789

I am trying to build a navigation bar in React. I am using redux-toolkit store to manage my state. Whenever I click on a link on the Navigation Bar, the redux store resets to the initial state. How do I build a navigation bar link that will not reset the redux store?

My NavBar -

import {
  Breadcrumbs,
  Link,
} from '@material-ui/core';

<Breadcrumbs aria-label="breadcrumb">
 <Link href="/">
   Home
 </Link>
</Breadcrumbs>

My dataSlice -

export const dataSlice = createSlice({
  name: 'data',
  initialState: {
    data: 'data'
  },
  reducers: {
    setData: (state, action) => {
      state.data = action.payload;
    },
  },
});

My store

export default configureStore({
  reducer: {
   data: dataReducer,
  },
});
1 Answers

I'm posting this as an answer since I guess my comment worked!

The Link that you are importing from @material-ui/core is just for styling purposes. It renders a plain a tag and clicking that link will cause a hard reload of the page.

You need to be using the Link component from react-router-dom. This component handles internal navigation via the to property instead of href. This will cause the page to navigate while still maintaining the Redux store and any other app state.

You can probably combine the two components to get the material-ui styling. But the important thing is that the navigation needs to go through react-router-dom.

Related