Skip to content

Instantly share code, notes, and snippets.

@gre
Created September 30, 2016 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gre/155864bdbe3c65918976dba3ca1b22fa to your computer and use it in GitHub Desktop.
Save gre/155864bdbe3c65918976dba3ca1b22fa to your computer and use it in GitHub Desktop.
in React / React Native, simulate bad network (lag / error) to debug how your app behaves with images
import React, {
Component,
PropTypes,
} from "react";
export default conf => (ImageC, renderEmpty) => {
const {
delay,
delayRandomness,
errorRandomness,
} = {
delay: 1000,
delayRandomness: 0.2,
errorRandomness: 0,
...(typeof conf==="object" ? conf : null),
};
class UnreliableImage extends Component {
static propTypes = {
style: PropTypes.any,
onError: PropTypes.func,
}
state = {
done: false,
};
onDone = () => {
if (Math.random() < errorRandomness) {
this.props.onError && this.props.onError({
nativeEvent: {
error: "UnreliableImageError"
}
});
}
else {
this.setState({ done: true });
}
};
componentWillMount () {
this._timeout = setTimeout(
this.onDone,
delay * ((1-delayRandomness) + delayRandomness * Math.random()),
);
}
componentWillUnmount () {
clearTimeout(this._timeout);
}
render () {
return this.state.done
? <ImageC {...this.props} />
: renderEmpty(this.props);
}
}
return UnreliableImage;
};
import React, {
Component,
} from "react";
import {
Image as RNImage,
View,
} from "react-native";
const debugImage =
__DEV__
? { "delay": 2000, "delayRandomness": 0.2, "errorRandomness": 0.4 }
: null;
const Image =
debugImage
? decorateUnreliableImage(debugImage)(RNImage, ({ style }) => <View style={style} />)
: RNImage;
import React, {
Component,
} from "react";
const debugImage =
__DEV__
? { "delay": 2000, "delayRandomness": 0.2, "errorRandomness": 0.4 }
: null;
const Image =
debugImage
? decorateUnreliableImage(debugImage)("img", ({ style }) => <div style={style} />)
: "img";
@ptmt
Copy link

ptmt commented Sep 30, 2016

Thanks, that would be very useful due to recent Image regressions. I solved mine by accurately rewriting some components with too many setState which caused didMoveToWindow for Image and multiple cancellations.
Maybe it should be placed into React Native tests?

@gre
Copy link
Author

gre commented Sep 30, 2016

sure :) please reuse/adapt to whatever need ;)

I personally use it to check some higher component handle nicely the onLoad / onError cases and render consistently to this.

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