How to return data from function by fetch() in React-Native - react-native

I created a FlastList for my posts where I calling a function that made for returning the likes of the post but it's giving me an error that is :
[Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
in RCTView (at Testing.js:196)
in TouchableWithoutFeedback (at Testing.js:185)
in RCTView (at Testing.js:184)
in RCTView (at Testing.js:165)
in TouchableWithoutFeedback (at Testing.js:160)
in RCTView (at VirtualizedList.js:1925)
in CellRenderer (at VirtualizedList.js:767)
in RCTView (at ScrollView.js:1038)
in RCTScrollView (at ScrollView.js:1178)
in ScrollView (at VirtualizedList.js:1183)
in VirtualizedList (at FlatList.js:676)
in FlatList (at Testing.js:151)
in RCTView (at Testing.js:147)
in Testing
in SceneView (at StackView.tsx:269)
in RCTView (at CardContainer.tsx:171)
in RCTView (at CardContainer.tsx:170)
in RCTView (at Card.tsx:455)
in RCTView (at createAnimatedComponent.js:151)
in AnimatedComponent (at Card.tsx:442)
in PanGestureHandler (at Card.tsx:435)
in RCTView (at createAnimatedComponent.js:151)
in AnimatedComponent (at Card.tsx:431)
in RCTView (at Card.tsx:424)
in Card (at CardContainer.tsx:138)
in CardContainer (at CardStack.tsx:503)
in RCTView (at CardStack.tsx:110)
in MaybeScreen (at CardStack.tsx:496)
in RCTView (at CardStack.tsx:93)
in MaybeScreenContainer (at CardStack.tsx:403)
in CardStack (at StackView.tsx:384)
in KeyboardManager (at StackView.tsx:382)
in RNCSafeAreaView (at src/index.tsx:26)
in SafeAreaProvider (at SafeAreaProviderCompat.tsx:34)
in SafeAreaProviderCompat (at StackView.tsx:379)
in StackView (at StackView.tsx:41)
in StackView (at createStackNavigator.tsx:33)
in Unknown (at createNavigator.js:80)
in Navigator (at createAppContainer.js:430)
in NavigationContainer (at renderApplication.js:40)
in RCTView (at AppContainer.js:101)
in RCTView (at AppContainer.js:119)
in AppContainer (at renderApplication.js:39)]
fetch() is working properly I'm getting the likes but when I return the data I got that error.
I don't understand why I'm getting this error and how it will remove and how I'll get posts like on my app.
Here is my code.
likes = async item => {
const response = await fetch(
'http://192.168.0.3:1234/post_likes?post_id=' + item.id,
);
const data = await response.json();
let likes = data[0].likes;
console.log(likes);
return <Text>{likes}</Text>;
};
render() {
return (
<View style={styles.container}>
<HeaderIcon />
{this.state.loading && <ActivityIndicator size="large" color="cyan" />}
<FlatList
onScroll={({nativeEvent}) => {
if (this.isCloseToBottom(nativeEvent)) {
this.getMorePost();
}
}}
data={this.state.post}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => (
<TouchableWithoutFeedback
style={styles.main}
onPress={() => {
this.openPost(item);
}}>
<View style={styles.main}>
<View style={styles.row}>
{/* <View>{this.img(item)}</View> */}
<View>
<Image
style={styles.profilePic}
source={{uri: item.featuredImage}}
/>
</View>
<View>
<Text style={styles.title}>{item.post_title}</Text>
</View>
</View>
<Image
// resizeMode="stretch"
style={styles.image}
source={{uri: item.featuredImage}}
/>
<View>
<TouchableWithoutFeedback
onPress={() => {
Share.share({
title: item.post_title,
message:
item.section_seo_url +
item.post_content.replace(/<[^>]*>| /g, ' ') +
item.featuredImage,
url: item.featuredImage,
});
}}>
<View
style={{
justifyContent: 'center',
padding: 10,
flexDirection: 'row',
}}>
<Image
source={require('../image/wlogo.png')}
style={{height: 40, width: 40, paddingLeft: 50}}
/>
{this.likes(item)}
</View>
</TouchableWithoutFeedback>
</View>
</View>
</TouchableWithoutFeedback>
)}
/>
</View>
);
}
}

As per me here you are making multiple api calls
Instead of that you can get your posts data with your likes from backend in simple
one api call.
You just need to add join query with your likes table in your get-posts request
which will return all your post with likes
So, you will get your all post with likes in one api call instead of these much
of calls.
Which is good practise for us.it will increase your app performance as well as
less api calls so it is good for server as well
Solution is like
add one more field likes to your post table
what you can do is when user like/dislike your post then get your likes
from post table and increment by one else decrement by one as per user
like/dislike and update back to post table.

Related

ERROR :Text string must be rendered within a <Text> component

I am writing this code for a message screen
<Screen>
<FlatList
data={Message}
keyExtractor={(Message) => Message.id.toString}
renderItem={({ item }) => (
<ListItem
title={item.title}
subtitle={item.description}
image={item.image}
onPress={() => console.log("message selected", item)}
/>
)}
ItemSeparatorComponent={ListItemSeparator}
/>
</Screen>;
And getting this error :
ERROR Error: Text strings must be rendered within a <Text> component.
This error is located at:
in RCTView (created by View)
in View (created by Screen)
in Screen (created by MessagesScreen)
in MessagesScreen (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
You should check that is text undefined. Like that;
<ListItem
title={item.title ? item.title : ""}
subtitle={item.description ? item.description : ""}
image={item.image}
onPress={()=>console.log("message selected", item)}/>

Stream IO Feeds React Native with React Navigation

I am using the Stream IO Feeds API for React Native. I was trying to follow this example but ended up getting this error when trying to run the app:
Error: Couldn't find a navigation context. Have you wrapped your app with 'NavigationContainer'? See https://reactnavigation.org/docs/getting-started for setup instructions.
This error is located at:
in FeedInner
in StreamAppConsumer (created by Feed)
in Feed (created by FlatFeed)
in FlatFeed (created by HomeFeed)
in StreamApp (created by HomeFeed)
in RCTView (created by View)
in View (created by HomeFeed)
in HomeFeed (created by SceneView)
in StaticContainer
in EnsureSingleNavigator (created by SceneView)
in SceneView (created by SceneView)
in RCTView (created by View)
in View (created by SceneView)
in SceneView (created by PagerViewAdapter)
in RNCViewPager (created by PagerView)
in PagerView (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by PagerViewAdapter)
in PagerViewAdapter (created by TabView)
in RCTView (created by View)
in View (created by TabView)
in TabView (created by MaterialTopTabView)
in MaterialTopTabView (created by MaterialTopTabNavigator)
in Unknown (created by MaterialTopTabNavigator)
in MaterialTopTabNavigator (created by App)
in EnsureSingleNavigator
in BaseNavigationContainer
in ThemeProvider
in NavigationContainerInner (created by App)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by SafeAreaView)
in SafeAreaView (created by App)
in RNCSafeAreaProvider (created by SafeAreaProvider)
in SafeAreaProvider (created by App)
in App (created by ExpoRoot)
in ExpoRoot
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
I noticed that this issue appears whenever I am using a Stream Flatfeed with a React navigation container. When the feed is on its own (not part of any stack/tab navigation), it renders correctly. I am testing the app on Android using Node v16.13.1. Any tips on this?
I was able to reproduce this issue on a smaller app:
Import statements:
import React, { Fragment } from 'react';
import { Text, View } from 'react-native';
import SafeAreaView from 'react-native-safe-area-view';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { NavigationContainer } from '#react-navigation/native';
import { createMaterialTopTabNavigator } from '#react-navigation/material-top-tabs';
import { StreamApp, FlatFeed, Activity, LikeButton, StatusUpdateForm, ReactionIconBar} from 'expo-activity-feed';
const Tab = createMaterialTopTabNavigator();
First tab (with Stream feed):
function Feed() {
return (
<StreamApp
apiKey={apiKey}
appId={appId}
token={token}>
<FlatFeed
Activity={props => (
<Fragment>
<Activity
{...props}
notify
Footer={
<ReactionIconBar>
<LikeButton {...props} />
</ReactionIconBar>
}
/>
</Fragment>)}/>
<StatusUpdateForm feedGroup='timeline' />
</StreamApp>
)
}
Second tab:
function Screen2() {
return (
<View style={{ flex: 1 }}>
<Text>Screen 2</Text>
</View>
);
}
Export (all of the code including the previous code is in App.js):
export default App = () => {
return (
<SafeAreaProvider>
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
<Tab.Navigator
screenOptions={{
tabBarLabelStyle: { fontSize: 12 },
tabBarItemStyle: { width: 100 },
}}
>
<Tab.Screen name="Feed" component={ Feed } />
<Tab.Screen name="Screen2" component={ Screen2 } />
</Tab.Navigator>
</NavigationContainer>
</SafeAreaView>
</SafeAreaProvider>
);
};
We asked a similar question on the GitHub repo for GetStream and found that we needed to upgrade to Expo 44 and downgrade expo-activity-feed to version 1.0.0 and ensure it does not have the ^ at the end of 1.0.0.
I hope this helps you as well.
Link to the GitHub Issue discussion https://github.com/GetStream/react-native-activity-feed/issues/244#issuecomment-1013567858

ViewPager of React Native is giving error 'View config not found for name RNCViewPager'

I am trying to use a simple ViewPager on React native. I am facing a problem when I try to run the app on an emulator. (I have not tested it on IOS and I don't require to test it too.)
So, I have a very simple piece of code -
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import ViewPager from '#react-native-community/viewpager';
const ViewPager_3 = () => {
return (
<View style={{ flex: 1 }}>
<ViewPager style={styles.viewPager} initialPage={0}>
<View style={styles.page} key="1">
<Text>First page</Text>
<Text>Swipe ➡️</Text>
</View>
<View style={styles.page} key="2">
<Text>Second page</Text>
</View>
<View style={styles.page} key="3">
<Text>Third page</Text>
</View>
</ViewPager>
</View>
);
};
const styles = StyleSheet.create({
viewPager: {
flex: 1,
},
page: {
justifyContent: 'center',
alignItems: 'center',
},
});
export default ViewPager_3;
When I try to run the code on Android emulator it gives an error on the page, find below--
Invariant Violation: View config not found for name RNCViewPager.
This error is located at:
in RNCViewPager (at ViewPager.js:174)
in ViewPager (at ViewPager_3.js:8)
in RCTView (at ViewPager_3.js:7)
in ViewPager_3 (created by SceneView)
in SceneView (created by CardContainer)
in RCTView (created by CardContainer)
in RCTView (created by CardContainer)
in RCTView (created by Card)
in RCTView (at createAnimatedComponent.js:151)
in AnimatedComponent (created by PanGestureHandler)
What could be the reason for the same?

FlatList renderItem error, TypeError: undefined (evaluating 'item.id')

I have a FlatList where I put some data in from my database.
In the render method, the state.data is correctly displayed when I console.log it. But in the renderItem method I try to print the item object but it doesn't display and then the error appears:
TypeError: undefined is not an object (evaluating 'item.id')
This error is located at:
in VirtualizedList (at FlatList.js:662)
in FlatList (at PlanView.js:49)
in RCTView (at View.js:44)
in TestLocalisation (at App.js:9)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)
I tried to fill the flatlist data with some random static data and it works perfectly.
There is my code:
render() {
console.log("render => " + JSON.stringify(this.state.data));
return (
<View style={styles.container}>
<Button
style={styles.button}
onPress={this.addTraining}
title="ADD">
</Button>
<FlatList
data={this.state.data}
extraData={this.state}
renderItem={({ item }) =>
<View>
<Text>{item.name}</Text>
<Text>{item.sport}</Text>
<Text>{item.time}</Text>
<Text>{item.distance}</Text>
</View>}
keyExtractor={item => item.id}
/>
</View>
);
}
And this is what is logged in the render function:
render => {
"_array":[
{"id":1,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":2,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":3,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":4,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":5,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":6,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":7,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":8,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":9,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":10,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":11,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":12,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":13,"name":"lol","sport":"running","time":120392,"distance":30},
{"id":14,"name":"lol","sport":"running","time":120392,"distance":30}
],"length":14}
The issue is in the function supplied to the renderItem prop. The function will be called once for each item of you array.
Your renderItem function destructures the object which it receives and tries to read the value for the key item. In the object it receives there is no key item, therefore item will be undefined and the access of item.name will fail.
To resolve the issue you must refactor the function supplied to renderItem to destrcuture that object correctly:
renderItem={({ name, sport, time, distance }) =>
<View>
<Text>{name}</Text>
<Text>{sport}</Text>
<Text>{time}</Text>
<Text>{distance}</Text>
</View>}
or not use destrcuturing at all:
renderItem={item =>
<View>
<Text>{item.name}</Text>
<Text>{item.sport}</Text>
<Text>{item.time}</Text>
<Text>{item.distance}</Text>
</View>}
Note the difference regarding the curly brackets between
const withDestrcuturingFn = ({ a, b, c }) => console.log(a)
and
const withoutDestrcuturingFn = (object_with_props_abc) => console.log(object_with_props_abc.a)

Error rendering stateless component: "Can't find variable: React"

I have a stateless component in my react-native application defined as follows.
components/TodoItem.js:
import { View, Text, Button } from 'react-native';
const TodoItem = () => (
<View style={{flex: 1, flexDirection: 'column'}}>
<Text>Hello, please remember to do this!</Text>
<Button
color="#841584"
title="Button 1"
/>
<Button
color="#241584"
title="Button 2"
/>
</View>
);
export default TodoItem;
When I use it in the render() function of App.js like this:
import TodoItem from './components/TodoItem';
// . . . other code here
render() {
return (
<View style={styles.container}>
<Text>Hello :)</Text>
<TodoItem/>
</View>
);
}
I get the following error:
ReferenceError: Can't find variable: React
This error is located at:
in TodoItem (at App.js:39)
in RCTView (at View.js:60)
in View (at App.js:37)
in App (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)
* components/TodoItem.js:4:8 in TodoItem
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:9050:17 in mountIndeterminateComponent
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:9573:10 in beginWork
- ... 21 more stack frames from framework internals
Some help with this is much appreciated!
You should add this - import React from 'react'; although you don't use React on components/TodoItem.js:
Even in a stateless component, we need to import React from react package as such:
import React from 'react';