react-native-webview-js-context
react-native-webview-js-context copied to clipboard
Chart loads the first time and does not reload after navigating away
When I'm in a renderedScene(page/ view) in <Navigator/>, it loads the first time fine. Then, I navigated to another scene(page/ view), and comes back to the same view, the chart doesn't load. It seems like componentWillMount
is being called, but it does not resolve with finish createWithHTML
. Therefore, it does not call: evaluateScript
.
componentWillMount() {
console.log('componentWillMount');
WebViewJSContext.createWithHTML(GC_HTML)
.then(context => {
console.log('finish createWithHTML');
this.ctx = context;
this.loadChart();
});
}
I have same problem and I think the reason like you. I think many WebViewJSContext instance is not good idea. So I only create 1 global WebViewJSContext for my project and don't destroy it.
I have a file GetCtx.js
import WebViewJSContext from 'react-native-webview-js-context';
const GC_HTML = `
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(resolve); /* <--- resolve() is called by RNWebViewJSContext */
</script>
</head>
<body><div id="chart_div"></div></body>
</html>
`;
let globalCtx = null;
export const getCtx = async () => {
if(!globalCtx){
globalCtx = await WebViewJSContext.createWithHTML(GC_HTML);
}
return globalCtx;
}
then, in chart component, just call
// 1 - import your function
import { getCtx } from 'PATH/TO/YOUR/GetCtx';
// 2 - set component variable ctx as global ctx
componentWillMount() {
getCtx().then(context => {
this.ctx = context;
this.loadChart(); // your function to load your chart here
})
}
// 3 - do NOT destroy ctx when unmount component
NOTE: do NOT destroy ctx when unmount component