merge persistedState by keys

Summary: Pushing all new rows into an array could result in duplicate entries. Now the data is stored in an object, using the row's id as a key. This deduplicates the data.

Reviewed By: jknoxville

Differential Revision: D15200794

fbshipit-source-id: 6afa2b7d02c1bdb796c250400938c38c51fdd207
This commit is contained in:
Daniel Büchele
2019-05-03 10:49:43 -07:00
committed by Facebook Github Bot
parent 37101cd1a7
commit 16ed255e2d

View File

@@ -36,11 +36,11 @@ function renderSidebar(row: Row) {
} }
type State = { type State = {
selectedIndex: number, selectedID: ?string,
}; };
type PersistedState = { type PersistedState = {
data: Array<Row>, [key: string]: Row,
}; };
export default class SeaMammals extends FlipperPlugin< export default class SeaMammals extends FlipperPlugin<
@@ -48,9 +48,7 @@ export default class SeaMammals extends FlipperPlugin<
void, void,
PersistedState, PersistedState,
> { > {
static defaultPersistedState = { static defaultPersistedState = {};
data: [],
};
static persistedStateReducer = ( static persistedStateReducer = (
persistedState: PersistedState, persistedState: PersistedState,
@@ -59,7 +57,8 @@ export default class SeaMammals extends FlipperPlugin<
) => { ) => {
if (method === 'newRow') { if (method === 'newRow') {
return { return {
data: [...persistedState.data, payload], ...persistedState,
[payload.id]: payload,
}; };
} }
return persistedState; return persistedState;
@@ -71,29 +70,30 @@ export default class SeaMammals extends FlipperPlugin<
alignItems: 'flex-start', alignItems: 'flex-start',
alignContent: 'flex-start', alignContent: 'flex-start',
flexGrow: 1, flexGrow: 1,
overflow: 'scroll',
}); });
state = { state = {
selectedIndex: -1, selectedID: null,
}; };
render() { render() {
const {selectedIndex} = this.state; const {selectedID} = this.state;
const {data} = this.props.persistedState; const {persistedState} = this.props;
return ( return (
<SeaMammals.Container> <SeaMammals.Container>
{data.map((row, i) => ( {Object.entries(persistedState).map(([id, row]) => (
<Card <Card
{...row} {...row}
onSelect={() => this.setState({selectedIndex: i})} onSelect={() => this.setState({selectedID: id})}
selected={i === selectedIndex} selected={id === selectedID}
key={i} key={id}
/> />
))} ))}
<DetailSidebar> <DetailSidebar>
{this.state.selectedIndex > -1 && {typeof selectedID === 'string' &&
renderSidebar(this.props.persistedState.data[selectedIndex])} renderSidebar(persistedState[selectedID])}
</DetailSidebar> </DetailSidebar>
</SeaMammals.Container> </SeaMammals.Container>
); );