How do you maintain selected item in list in reactjs/redux application?

2.2k Views Asked by At

I am new to the reactjs/redux world of applications. I am creating a web application with a page layout where the left side has a list of names and the right side displays the details of the selected name.

Using redux, when a name is selected from the list, the application dispatches an ajax call to fetch the details. This ultimately updates the redux state with the selected details and causes the details component to update with the information.

The list of names is created using ag-grid, so it has the ability to highlight the selected item. But once the redux state is updated all the components seem to rerender and the selected item in the list is no longer selected. I guess in general, the state of the list of names goes back to the initial state when the page loads (i.e. if the list was filtered it is no longer filtered).

How do I maintain the selected item (and really everything else done on that list) before selecting an item? I'm almost thinking that I have to maintain the grid state in my redux state as well...but is that right? Is that the only option I have?

The structure of my components are a container component (WSContainer) which has two children, NameTable and NameDetails.

2

There are 2 best solutions below

0
On BEST ANSWER

I would suggest that you dispatch an action that saves the selectedId int the redux state. I would also suggest storing each detail you get back in an object with the id as the key and the details as the value

detailsById: {
  id1: detail1,
  id2: detail2
},
selectedId: id1

This will make it so you don't have to wait for an ajax call to return before you display the detail. At that point, you just display the detail data that matches the id you saved as you selectedId.

Check this out for more info on redux actions.

0
On

Why don't you keep the value, index, or text of the selected item within the state? Then, as the page renders, you can use the componentDidMount or componentWillMount method to highlight the selected name (or whatever else you want to do).

https://facebook.github.io/react/docs/react-component.html