Skip to content

Instantly share code, notes, and snippets.

@SamyPesse

SamyPesse/output Secret

Last active March 14, 2018 15:48
Show Gist options
  • Save SamyPesse/4950194a9ca47c3d91e1226d93b3e802 to your computer and use it in GitHub Desktop.
Save SamyPesse/4950194a9ca47c3d91e1226d93b3e802 to your computer and use it in GitHub Desktop.
Test bug react-tree-walker
fetch 0
render { rest: 2, id: 0 }
done !
fetch 1
render { id: 1, rest: 1 }
fetch 2
fetch 2
render { id: 2, rest: 0 }
render { id: 2, rest: 1 }
fetch 3
fetch 3
fetch 3
render { id: 3, rest: 0 }
render { id: 3, rest: 0 }
fetch 4
fetch 4
fetch 4
fetch 4
fetch 5
fetch 5
render { id: 4, rest: 0 }
fetch 5
fetch 6
import * as React from 'react';
import reactTreeWalker from 'react-tree-walker';
class Foo extends React.Component {
state = {
ready: false
};
getData = () => {
console.log('fetch ', this.props.id);
return new Promise((resolve, reject) => {
setTimeout(() => {
this.setState({
ready: true
});
resolve();
}, 1000);
});
};
render() {
if (this.props.rest < 0) {
return 'Yo !';
}
if (!this.state.ready) {
return null;
}
console.log('render ', this.props);
const id = this.props.id;
return (
<div>
<Foo id={id + 1} rest={this.props.rest - 1} />{' '}
<Foo id={id + 2} rest={this.props.rest - 1} />
</div>
);
}
}
function visitor(element, instance, context) {
if (instance && typeof instance.getData) {
return instance.getData();
}
return true;
}
reactTreeWalker(<Foo rest={2} id={0} />, visitor).then(() => {
console.log('done !');
});
@ctrlplusb
Copy link

ctrlplusb commented Mar 14, 2018

Can you try change line 46 to:

      return instance.getData().then(() => true);

Resolving a falsey value within the visitor should stop the traversal and resolve the entire tree walking promise, whilst resolving a truthy value will indicate that you wish to continue traversing down the tree. This provides me with an optimisation strategy where I can bail out of the tree walking early if I like.

I think because you were originally resolving undefined it caused the immediate bail out after the first getData call. The strange thing is that the other instances still got hit. I will have to look into that. I wouldn't have expected that to occur.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment