简体   繁体   中英

How to return data from function by fetch() in 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(/<[^>]*>|&nbsp;/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM