2

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,
  },
});
yihom78241
  • 73
  • 6
  • I believe your question could be answered by https://stackoverflow.com/questions/47982635/redux-state-resets-on-window-reload-client-side. The reason is that a redirect is functionally no different than just reloading the page, assuming that the domain is the same. I.E. you're still on the same site. If it doesn't answer your question let me know. If it does still let me know so that we can link to the other question for future users reference. Also, welcome to stack overflow. – R Esmond Mar 15 '21 at 19:10
  • 3
    You can fix this by using react-router-dom to handle your navigation and using the `Link` component from react-router-dom to navigate without fully reloading the page. – Linda Paiste Mar 15 '21 at 19:21
  • In that case Linda Paiste's answer will work. It involves using an entirely new library to simulate navigation, but if you want to avoid localStorage that's what you kind-of need. Basically what you're asking for is how to build a Single-Page application—one which navigates without redirection. – R Esmond Mar 15 '21 at 19:26
  • @LindaPaiste Your solution works. Thank you. – yihom78241 Mar 15 '21 at 19:32
  • @yihom78241 Are you already using react-router-dom to handle routing? And just used the wrong `Link` component? – Linda Paiste Mar 15 '21 at 19:34
  • @LindaPaiste Yes that is what happened. – yihom78241 Mar 19 '21 at 11:00

1 Answers1

3

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.

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102