Skip to content

Commit

Permalink
Fix fetch more lines button FlatList issue
Browse files Browse the repository at this point in the history
It seems FlatList is unhappy with the previous implementation of the
fetch more lines button. Simplify by pulling out to a self-contained
function component and remove the state from Buffer.
  • Loading branch information
mhoran committed Mar 1, 2024
1 parent 99e75c1 commit 5ab937d
Showing 1 changed file with 27 additions and 38 deletions.
65 changes: 27 additions & 38 deletions src/usecase/buffers/ui/Buffer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,33 @@ interface Props {
fetchMoreLines: (lines: number) => void;
}

interface State {
desiredLines: number;
bufferId: string;
}

const keyExtractor = (line: WeechatLine) =>
line.pointers[line.pointers.length - 1];

export default class Buffer extends React.PureComponent<Props, State> {
static readonly DEFAULT_LINE_INCREMENT = 300;
const Header = (props: {
lines: number;
fetchMoreLines: (lines: number) => void;
}) => {
const [desiredLines, setDesiredLines] = React.useState(props.lines);

linesList = React.createRef<FlashList<WeechatLine>>();
if (props.lines < desiredLines) return;

state = {
desiredLines: Buffer.DEFAULT_LINE_INCREMENT,
bufferId: this.props.bufferId
};
return (
<Button
title="Load more lines"
onPress={() => {
const next = desiredLines + Buffer.DEFAULT_LINE_INCREMENT;
props.fetchMoreLines(next);
setDesiredLines(next);
}}
/>
);
};

static getDerivedStateFromProps = (props: Props, state: State) => {
if (props.bufferId !== state.bufferId)
return {
desiredLines: Buffer.DEFAULT_LINE_INCREMENT,
bufferId: props.bufferId
};
else return null;
};
export default class Buffer extends React.PureComponent<Props> {
static readonly DEFAULT_LINE_INCREMENT = 300;

linesList = React.createRef<FlashList<WeechatLine>>();

componentDidUpdate(prevProps: Props) {
const { bufferId } = this.props;
Expand All @@ -67,23 +68,6 @@ export default class Buffer extends React.PureComponent<Props, State> {
);
};

renderMoreLinesButton = () => {
const { lines } = this.props;
if (lines.length < this.state.desiredLines) return;

return (
<Button
title="Load more lines"
onPress={() => {
const desiredLines =
this.state.desiredLines + Buffer.DEFAULT_LINE_INCREMENT;
this.props.fetchMoreLines(desiredLines);
this.setState(() => ({ desiredLines }));
}}
/>
);
};

render(): JSX.Element {
const { lines } = this.props;
return (
Expand All @@ -94,7 +78,12 @@ export default class Buffer extends React.PureComponent<Props, State> {
keyboardDismissMode="interactive"
keyExtractor={keyExtractor}
renderItem={this.renderBuffer}
ListFooterComponent={this.renderMoreLinesButton}
ListFooterComponent={
<Header
lines={lines.length}
fetchMoreLines={this.props.fetchMoreLines}
/>
}
estimatedItemSize={44}
/>
);
Expand Down

0 comments on commit 5ab937d

Please sign in to comment.