How can I Refresh Web View in React Native? - react-native

I have a webview as tab A and a todolist flatlist on tab B. If the user adds an entry to the flatlist on tab B, i want the tab A webview to refresh.
I couldn't find any .refresh() or reload() methods on the webview control https://facebook.github.io/react-native/docs/webview.html
Any ideas how to accomplish this?

You can set a key to the webview
key={this.state.key}
and then you can reload it by updating the state
this.setState({ key: this.state.key + 1 });

Well I reload WebView by doing following:
render() {
let WebViewRef;
return (
<View style={Style1.container}>
<WebView
ref={WEBVIEW_REF => (WebViewRef = WEBVIEW_REF)}
source={{ uri: this.state.site }}
renderLoading={this.ActivityIndicatorLoadingView}
startInLoadingState={true}
/>
<Button title="Reload Me!" onpress={() => { WebViewRef && WebViewRef.reload(); }} />
</View>
)
}
In this code I Declare Reference Variable WebViewRef first then assign this to WebView as ref={WEBVIEW_REF => (WebViewRef = WEBVIEW_REF)} and then call this reference for reload() as ()=>{ WebViewRef && WebViewRef.reload();}

The react-native-community/react-native-webview component has a .reload() method on the ref.
const webViewRef = useRef();
// ...
return (
<WebView ref={(ref) => webViewRef.current = ref} ... />
)
// ...
You can then use the following to reload:
webViewRef.current.reload();

I ended up using a dummy query parameter to signal a refresh of the web view:
In Tab B, I dispatch a change which changes "latestItemId" in the global state.
In Tab A, I use mapStateToProps which maps to <WebView source={{uri:URL?latestItemId=${latestItemId}}} /> in the render method. This causes it to think it's a new url and reload it.

Reload was not working on my end.
If you want to refresh on focus change you can use the hook useFocusEffect of react navigation and in the unmount clean the URL used in the webview. Then in the initialize you need to set that again. Maybe using a a useState.
useFocusEffect(
useCallback(() => {
setUrl(url!);
return () => {
setUrl(undefined);
};
}, [url]),
);

In my case I have source={{html}} so refresh() won't work in that situation. However, in my case I am still able to inject javascript so I can set some properties specifically document.styles.body.color to match dark and light mode.
const fg = colorScheme === "light" ? "black" : "white";
const webViewRef = createRef<WebView>();
useEffect(() => {
webViewRef.current?.injectJavaScript(`
document.body.style.color='${fg}';
true
`);
}, [fg]);
...
<WebView
ref={webViewRef}
originWhitelist={["*"]}
style={{
height: 200,
backgroundColor: "transparent",
}}
onMessage={() => {}}
javaScriptEnabled={true}
injectedJavaScript={`
document.body.style.color='${fg}';
true;`}
source={{ html }}
/>

Related

react native textinput lost focus after 1 char type

I have this problem with ios but not with android. It only disturb the add task input the task edit and the list name edit. The input addList(It's the one with "What to do?" on the draw) in the header works fine.
UI drawing
Achitecture of components
I console log my component and I can see it rerender everytime I add a letter in the input field.
I checked on google and follow this:(can we link other website here?) https://www.codegrepper.com/code-examples/javascript/react+native+textinput+lost+focus+after+charter+type
Tried the the first solution with onBlurr and onFocus.
I tried to make a TextInput component for add task.
I even try with my component addList but it didn't solve the problem.
Anyone have faced this problem before? Is there anyway to by pass this?
My code without the import/style look like this:
const TaskList: FunctionComponent<TasksListProps> = ({
addTask,
deleteTask,
toggleTask,
editTaskName,
...props
}) => {
console.log('props', props);
const [nameOfTask, setNameOfTask] = useState('');
console.log('name', nameOfTask);
const textHandler = (enteredName: string) => {
setNameOfTask(enteredName);
};
const handleSubmitTask = () => {
if (nameOfTask === '') {
return;
}
addTask(props.listId, nameOfTask);
setNameOfTask('');
};
return (
<View style={styles.tasksListContainer}>
{props.tasks.map(task => (
<SingleTask
key={task.id}
task={task}
listId={props.listId}
deleteTask={deleteTask}
toggleTask={toggleTask}
editTaskName={editTaskName}
/>
))}
<View style={styles.taskInputContainer}>
<TextInput
style={styles.tasksTextInput}
value={nameOfTask}
onChangeText={textHandler}
placeholder="Write a task to do"
/>
<TouchableOpacity onPress={handleSubmitTask}>
<Image source={require('./Img/add-button.png')} />
</TouchableOpacity>
</View>
</View>
);
};
You can create a HOC and wrap your screen width DismissKeyboard
import { Keyboard } from 'react-native';
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
That because Re render.
Try to make the input with the main component of the page to test it.
Then check where the error with re-render

useEffect not working in custom drawer component without refresh

So I am using react-navigation 5 and I have a custom drawer component for my app. I want to display the name of the logged-in user in the drawer for which I am using a state variable and I am updating the state from firestore. I am calling a function in useEffect which accesses firestore and gets the name of the user. But I think the useEffect is not working without refresh because unless I save the project and refresh the application the state is not getting updated in the application and I cannot see the name of the user without refreshing but it is visible after a refresh. Any ideas why this is happening? Any help would be appreciated. Thank you.
Custom drawer
export default function CustomDrawer(props) {
const paperTheme = useTheme();
const [name,setName]=useState('');
useEffect(() => {
doStuff();
}, []);
const doStuff = async () => {
var phone=global.phone;
await firestore().collection("Users").where('Phone Number', '==', phone).get().then(querySnapshot=>{
querySnapshot.forEach(documentSnapshot => {
console.log("in drawer");
console.log(documentSnapshot.data());
setName(documentSnapshot.data().Name);
})
})
};
return(
<View style={{flex:1}}>
<DrawerContentScrollView {...props}>
<View style={styles.drawerContent}>
<View style={styles.userInfoSection}>
<View style={{flexDirection:'row',marginTop: 15}}>
<Avatar.Image
source={{
uri: ''
}}
size={50}
/>
<View style={{marginLeft:15, flexDirection:'column'}}>
<Title style={styles.title}>{name}</Title>
</View>
</View>
</View>
</View>
</DrawerContentScrollView>
</View>
);
}
Looks like you have doStuff function defined outside the useEffects.
Either you need to put it inside useEffects or add it in dependency list
useEffect(() => {
doStuff();
}, [doStuff]);

Calling modal on a list of products opens the modal for all of them instead of just the one being clciked

I am making a react native app that loads data from google firebase and then display it on a page, when a user clicks on any of the products aa modal will open to show more datails.
I am using useEffect to load the data on page load then display then results:
const fetchData = async () => {
const categories = db.collection("productsDB");
const collections = await categories
.limit(6)
.onSnapshot((querySnapshot) => {
const items = [];
querySnapshot.forEach((documentSnapshot) => {
items.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
});
setItems(items);
setLoading(false);
});
return () => collections();
};
useEffect(() => {
fetchData();
}, []);
and the show them like this:
{loading ? (
<ActivityIndicator />
) : (
items.map((item) => (
<TouchableOpacity
style={styles.queryResult}
key={item.key}
onPress={() => {
setModalVisible(!modalVisible);
}}
>
<View style={styles.queryResultContent}>
<Image
style={{ width: 100, height: 100 }}
source={{ uri: String(item.images) }}
/>
<View>
<Text style={styles.queryInfoHeader}>{item.name}</Text>
</View>
</View>
<View>
<ProductModal
isModalVisible={modalVisible}
setModalVisible={setModalVisible}
navigation={navigation}
{...item}
/>
</View>
</TouchableOpacity>
))
)}
when I open the modal, it opens the modal for all of the products and doesnt really matter if I click on the first product or what, it opens all of the modals, and I am not sure how to get rid of this!
is there any better way to write this function?
You're using the same modalVisible flag for all of your modals; therefore, they either are all visible or all hidden.
Why not have a single modal rather than rendering a bunch of them in the loop, and pass the item as a prop to it?

React Native ref is undefined until page reload

I am using refs to animate a View, but the refs are throwing an undefined error. However, if I comment-out my attempt to access the ref, load the page, un-comment the code, & reload the page, the animation works fine.
My code:
export const AccountScreen = ({ navigation }) => {
return (
<SafeAreaView style={{ backgroundColor:'#FFFFFF', flex: 1 }}>
<Animatable.View style={styles.container} ref={ref => {this.containerRef = ref}}>
</Animatable.View>
</SafeAreaView>
)
};
launchOpenAnimation()
function launchOpenAnimation () {
this.containerRef.animate(appearContainerAnimation); //If I comment this out, reload, and un-comment, it works
}
What can I do to fix this? It appears that the ref isn't defined at the time that my launchOpenAnimation() is executed, but that it is defined after, thus resulting in the code working if I comment it out, reload, un-comment, and reload again.
First thing first, your question is messed up between calls component and functional component, cuz there is no this in functional component. I'll convert them to function component using useRef and useEffect
In the first run this.containerRef have not be assign to ref of Animatable yet.
Try this
export const AccountScreen = ({ navigation }) => {
const animateRef = useRef()
useEffect(() =>{
launchOpenAnimation()
function launchOpenAnimation () {
// add ? to make sure animate is called only when this.containerRef exists
containerRef?.current.animate(appearContainerAnimation);
}
},[])
return (
<SafeAreaView style={{ backgroundColor:'#FFFFFF', flex: 1 }}>
<Animatable.View style={styles.container} ref={ref => {
ref.animate(appearContainerAnimation); // add this if you need to run when initial render run
animateRef.current = ref
}}>
</Animatable.View>
</SafeAreaView>
)
};

React-Native re-render Flatlist

I'm having trouble keeping the data in my Flatlist after coming back from another page. My scenario is as follows:
User goes to homepage and scrolls through 20 items
User clicks their profile tab changing page using react-native-router-flux
User clicks the home tab taking them back to the list however the list re-renders and starts from the top.
How can I stop this re-rendering and fetching the same data again?
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteReuest gets my data from firebase in batches of 5 and sets data: []
data: [...this.state.data, ...results]
I've tried using the below but not sure if this is correct, when i navigate away and back the data re-renders. I want to keep the data so the page will be exactly the same as when it was left.
shouldComponentUpdate(nextProps, nextState) {
if (JSON.stringify(this.state.data) !== JSON.stringify(nextState.data)) {
return true;
}
return false;
}
My flatlist:
<View>
<FlatList
scrollsToTop={false}
ref={(ref) => { this.flatListRef = ref; }}
showsHorizontalScrollIndicator={false}
onScroll={this.handleScroll}
data={this.state.data}
keyExtractor={item => item.key}
ListFooterComponent={this.renderFooter()}
onRefresh={this.handleRefresh}
refreshing={this.state.newRefresh}
onEndReached={this.handleEndRefresh}
onEndReachedThreshold={0.05}
getItemLayout={this.getItemLayout}
renderItem={this.renderItem}
/>
{this.state.refreshAvailable ? this.renderRefreshButton() : null}
</View>
Thanks for any help!
Coded long back for the dumb project, maybe this can help you
The View: used onLayout Prop for getting the y-axis
<ScrollView
ref={(ref) => this.scrollTo = ref}
contentContainerStyle={{margin:5,}}
>
<Card onLayout={(event) => this._findHeight(event.nativeEvent.layout, 'personal')}>
<Personal review={true}/>
</Card>
</ScrollView>
The Function: stored the y-axis; here i have used realm db
_findHeight = (e, name) => {
const {x, y, width, height} = e;
this.realm.write(() => {
this.realm.create('yLocation',{names:name,yaxis:y}) :
});
}
The AutoScroll Method: here i have used scrollTo method from ScrollView you can use any method using their ref
_scrollTo = (y) => {
this.scrollTo.scrollTo({x:0,y:y,animated:true});
}
Note : Call _scrollTo method in componentDidMount