The output does not show the response from the method in React Native

I am facing an issue with a method in my code (React Native).

I have an array of IDs and I need to send a 'GET' request for each ID to display a preview card for each.

To achieve this, I have used the 'map' method on my array. The request is successful and then I call my method cardUser(user) to display the preview card.

Here is the section of my code where I implement the map (which is working fine):

render() {
    if (!this.state.isLoaded) {
        return (
            <Spinner color='#84568c' />
        );
    } else {
        var user = this.state.user;
        return (
            <ScrollView
                refreshControl={
                    <RefreshControl
                        tintColor='#84568c'
                        refreshing={this.state.refreshing}
                        onRefresh={this._onRefresh.bind(this)} />
                }
            >
                <Content padder>
                     {user.following.map(following => (
                        this.getUserByID(following)
                     ))}
                </Content>
            </ScrollView>
        );
    }
}

I call getUserByID() (which is functioning properly):

getUserByID(id) {
    fetch(api.base_url + api.user_url + '/' + id, {
        method: "GET",
        headers: { 'Authorization': 'Bearer ' + this.state.token }
    })
    .then((response) => response.json())
    .then((responseData) => {
        this.cardUser(responseData);
    })
    .done();
}

After receiving the response in responseData, I want to display and style each user. Therefore, I call cardUser() with a user object each time.

cardUser(user) {
    console.log(user.id);
    return (
        <TouchableHighlight underlayColor='transparent' key={user.id}
            onPress={() => this.props.navigation.navigate('UserProfile', {id: user.id})} onLongPress={() => this.alertUserId(user.id)} >
            <View style={container.card}>
                    <View style={container.cardUser}>
                        <Image source={{uri: user.banner}} style={{position: 'absolute', width: '100%', height: 170, borderRadius: 20}} />
                        <View style={container.darkLayer}>
                            <Left>
                                <Thumbnail large source={{uri: user.photo}} style={{alignSelf: 'center'}}/>
                            </Left>
                            <Body>
                                <View style={{alignItems: 'center'}}>
                                    <Text style={text.pseudoHomepage}>{user.username}</Text>
                                    <Text style={[text.stats, {color: 'white'}]}>{user.first_name}</Text>
                                </View>
                            </Body>
                            <Right>
                                <Icon ios='ios-medal' android='md-medal' style={{color: 'white', alignSelf: 'center', fontSize: 40}}/>
                            </Right>
                        </View>
                        <View style={container.darkFooterLayer}>
                            <Text numberOfLines={2} style={text.bioFotter}>{user.bio}</Text>
                        </View>
                    </View>
            </View>
        </TouchableHighlight>
    );
}

However, nothing is being displayed... Even though if I use console.log(user), it shows the correct items in the logs! In the correct order with no duplicate objects or any other anomalies...

Furthermore, if I add a console.log(user) inside the return(), it still displays the correct information and no error or warning messages are shown.

I hope this explanation is clear. If you require more details, please let me know. Thank you and have a great day!

(Apologies for any misspelled words, English is not my native language)

Answer №1

In order to properly display the data, it is important to first fetch all the necessary information. This process cannot be done within the render method.

componentDidMount() {
  Promise.all(this.state.user.following.map(this.fetchUser))
    .then(userFetchedArray => this.setState({ usersList: userFetchedArray }))
}

fetchUser(id) {
  return fetch(api.base_url + api.user_url + '/' + id, {
    method: "GET",
    headers: { 'Authorization': 'Bearer ' + this.state.token }
  })
  .then((response) => response.json());
}

Once the data is fetched, it can then be rendered on the screen:

render() {
...
<Content padder>
  {this.state.usersList.map(this.cardUser)}
</Content>
...

The callback function passed to map should return jsx, but in your case, it is returning undefined (getUserByID function is returning nothing). Additionally, this callback cannot be an async function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips for enabling communication between the server and client

As someone who is new to the world of web development, please bear with me as I ask a question out of curiosity. I am wondering if there is a method for the server to push messages to clients. For instance, imagine a client's webpage featuring a news ...

Parsing JSON with the nodejs JSON.parse() method from the Stack Overflow API

Check out the code snippet below: const request = require('request'); const API = "https://api.stackexchange.com/2.2/users?page=1&order=desc&sort=reputation&site=stackoverflow"; request(API, function(e//console.dir(body); if( err || ...

Is it possible to update only the inner text of all elements throughout a webpage?

Scenario After coming across a thought-provoking XKCD comic, I decided to craft a script that would bring the comic's concept to life: javascript:var a=document.getElementsByTagName('body')[0].innerHTML;a=a.replace(/Program(\w\w+ ...

"Exploring the symbiotic relationship between Node.js and Express.js: an

I recently started learning Node.js and Express.js. I used the Express.js executable (express) to create an express application, which generated the following lines in app.js: ... var app = express(); http.createServer(app).listen(app.get('port' ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

Utilize jQuery to set a cookie, then apply the bodyclass retrieved from the cookie upon page

I have a button that changes the body class to .blackout For this, I am utilizing js-cookie library to manage cookies. The code snippet associated with my button is shown below: <script> $('#boToggle').on('click', function(e) { ...

Python Flask login screen not showing error message

Currently, I'm in the process of developing a login screen that incorporates Bootstrap and utilizes jQuery keyframes shaking effect. The backend functionality is managed by Flask. However, I seem to be encountering an issue where the error message "Wr ...

Has anybody managed to successfully implement this require or debug NPM module for use in a web browser?

Has anyone successfully implemented the require or debug NPM modules in a browser environment? Despite claims and instructions on the debug NPM module's page that it can be used in the browser, attempting to do so results in the following error: Unc ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

Warning in Vue 3: Production is being disrupted by "tags with side effects"

After recently upgrading from Vue 2 to Vue 3, I encountered a problem in my app where certain parts show a warning in development mode: [Vue warn]: Template compilation error: Tags with side effect (<script> and <style>) are ignored in client ...

Backbone - NestedModels - Issues with nested sets not triggering 'change' event

I have incorporated the Backbone nested plugin into my project. The way I set up my binding is as follows : var view = Backbone.View.extend({ initialize: function(params) { this.model.bind('change', _.bind(this.rerender, this)); ...

Dealing with problems in col-md display on tablet devices

When viewing on Full Screen and mobile, the ranges panel (class="col-md-3") displays correctly. However, on tablet screens, the left column is obscured by the youtube image panel (class="col-12 col-md-9"). I have attempted various adjustments to the div s ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

The integration of Node.js and Socket.io with Phaser.js is experiencing difficulty when connecting to socket.io with the parameters "?EIO=3&transport

My node.js server is up and running, and my phaser.js game is functioning as expected. However, I am facing an issue where the 'connected' console log is not displaying when the game runs. Instead, I am receiving this error message on the client ...

What are the potential disadvantages of relocating the login logic from the 'signIn()' function in NextAuth.js?

My experience with NextAuth.js for the first time has led me to realize that signing in using the Credentials provider can be a bit tricky when it comes to error handling. It seems like the default implementation should resemble something along these lines ...

Issue encountered when attempting to utilize filters with strapi V4 graphql and nextjs, functionality not working

Currently, I am using strapi V4 along with the graphql extension. Everything works fine when I use filters with variables in the graphql Playground. query getOrdersFilterList($searchstring: String!) { orders(filters: { customer: { contains: $searchstring } ...

The returned data from a Apollo Client useMutation call is consistently undefined

Currently, I have a code snippet that executes a mutation to update a post to "published." The mutation functions correctly and updates the data as intended. However, I am facing an issue where the data property remains undefined in the useMutation hook. S ...

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Utilizing Sequelize to Convert and Cast Data in iLike Queries

When using Sequelize for a full-text search, I encountered an issue with applying the iLike operator to columns of INTEGER or DATE type. How can I cast off a column in this case? To illustrate, here is an example of what I am trying to achieve with a Post ...