rubenmondom
rubenmondom

Reputation: 103

history.replace doesn't work in react router dom v5.2

I think that I'm doing something bad. I'm trying to reload the same url (/timetable) when click on an item of my list, but changing the state. But when I'm on that endpoint nothing happens when I click on other ListItem. I mean that I'm on /timetable with state = {semester: true}, and when I click on the second item nothing changes.

I take const history = useHistory from react-router-dom.

<List component="div" disablePadding>
          {HorarioElements.map(({ text, icon, route, state }) => (
            <StyledListItem
              button
              key={text}
              onClick={() => {
                history.replace('/timetable', state)
              }}
            >
              <ListItemIcon>{icon}</ListItemIcon>
              <ListItemText primary={text} />
            </StyledListItem>
          ))}
</List>

The HorarioElements array is the following:

const HorarioElements = [
  {
    text: '1er semestre',
    icon: <Filter1Icon />,
    state: { semester: true },
  },
  {
    text: '2do semestre',
    icon: <Filter2Icon />,
    state: { semester: false },
  },
]

Anyone knows what is the properly way to do this?

Upvotes: 0

Views: 2256

Answers (1)

Lionel Rowe
Lionel Rowe

Reputation: 5926

React Router history.replace's state isn't the same as your app state — it's state that's present on the history object itself. It's rare that you'd need to use this.

To change your app state while remaining on the same page, you need useState (for state scoped to a component or its direct children) or useContext (for state scoped to your whole app or a significant-sized subtree of your app).

Upvotes: 1

Related Questions