React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statement appears empty. Despite thorough debugging, it seems like the object retrieved from the database is indeed being passed through, containing content ready for display. Yet, this content fails to reach the return function. Various attempts have been made to fix this issue (including placing the return function inside the Firebase query), but so far nothing has proven successful. Below is the relevant code:

export default class RepsPage extends Component {

renderRep(repID){
        var rep = new Firebase('https://ballot-app.firebaseio.com/congressPerson');       
        var nameView;
        var partyView;
        //The entire function does not seem to execute properly
        rep.orderByChild("bioguideId").equalTo(repID).on("child_added", function(snapshot) {
            console.log(snapshot.val());

            nameView = <View style ={styles.tagContainer}>
                    <Text>{snapshot.val().name}</Text>
                    <Text>{snapshot.val().party}</Text>
               </View>
        });

        return (
            nameView
        );
}  

render(){ 
    var user = this.props.user;
    var reps = user.representatives;

    return (
        <ScrollView
            automaticallyAdjustContentInsets={false}
            scrollEventThrottle={200}
            style={styles.scrollView}
        >
                { reps.map(this.renderRep.bind(this)) }
        </ScrollView>
    );
}
}

Answer №1

Make sure to update your renderRep method by setting the state rather than returning a value.

Here is an example of how you can do this:

export default class RepresentativesPage extends Component {
    constructor() {
        this.state = {
            snapshots: []
        }
    }

    componentDidMount(){
        this.fetchRepresentative('someid');
    }

    fetchRepresentative(repID) {
        var rep = new Firebase('https://ballot-app.firebaseio.com/congressPerson');
        var nameView;
        var partyView;

        rep.orderByChild("bioguideId").equalTo(repID).on("child_added", (snapshot)=> {
            console.log(snapshot.val());
            this.setState({snapshots: [].concat(this.state.snapshots, [snapshot.val()])});
        });
    }

    renderRepresentative() {
        return this.state.snapshots.map((snapshot)=>
            <View style={styles.tagContainer}>
                <Text>{snapshot.name}</Text>
                <Text>{snapshot.party}</Text>
            </View>
        );
    }

    render() {
        var user = this.props.user;
        var representatives = user.representatives;

        return (
            <ScrollView
                automaticallyAdjustContentInsets={false}
                scrollEventThrottle={200}
                style={styles.scrollView}
            >
                { this.renderRepresentative.bind(this) }
            </ScrollView>
        );
    }
}

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

Handling an HTML Form without the Submit Button using VeeValidate

I've implemented a form handler using its composable feature in my <script setup>: const { submitForm, resetForm, handleSubmit, meta } = useForm() function save() { // Want to submit the form here submitForm() // Not working showSaveSnac ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

Incorporate an icon into a text input field using Material UI and React

I have a form with a text input element: <FormControl className='searchOrder'> <input className='form-control' type='text' placeholder='Search order' aria-label='Search&ap ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

Utilizing the NODE_ENV variable in a Windows 10 npm script

I have integrated webpack into a Typescript project. Following a helpful tutorial, I created 3 separate webpack configuration files: webpack.common.js webpack.production.js webpack.development.js In the tutorial's package.json, the "scripts" sectio ...

What is the best way to replace HttpClient in Aurelia?

I am completely new to Aurelia. How can I modify the code below in order to implement a dummy HttpClient, such as a json reader, that will provide a static set of json data without the need for a server during development? import {inject} from 'aure ...

The alignment of elements in the div seems to be slightly skewed

Currently, I am in the process of creating a website with the temporary name yeet.io. I am facing an issue where I am attempting to center both an input and h1 element inside a div vertically and horizontally, but they keep appearing misaligned for some r ...

Stop fullscreen mode in Angular after initiating in fullscreen mode

Issue with exiting full screen on Angular when starting Chrome in full-screen mode. HTML: <hello name="{{ name }}"></hello> <a href="https://angular-go-full-screen-f11-key.stackblitz.io" target="_blank" style=& ...

Issues with babel plugin-proposal-decorators failing to meet expectations

I recently included these two devDependencies in my package.json: "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-decorators": "^7.1.6", In the configuration file .babelrc, I have listed them as plugins: { "presets": ["m ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Using Key Press to Rotate Messages - Jquery

Need help with rotating an array based on alphanumeric key presses? Check out the code snippet I've been working on below. Unfortunately, I'm having trouble getting the loop to function properly. Any suggestions or feedback would be greatly appre ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo ...

Discover distinct and recurring elements

Having two sets of JSON data: vm.userListData = [{ "listId": 1, "permission": "READ" }, { "listId": 2, "permission": "WRITE" }, { "listId": 2, "permission": "READ" }, { "listId": 3, ...

Steps for returning a res.send(req.body) upon sending back to a function

I'm currently working on sending the req.body from a POST request route back to the executing function for further processing. The structure of req.body is as follows: { username: 'aa', password: 'ss' } After making the post requ ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...

Is there a way to prevent the annoying "Reload site? Changes you made may not be saved" popup from appearing during Python Selenium tests on Chrome?

While conducting automated selenium tests using Python on a Chrome browser, I have encountered an issue where a popup appears on the screen after reloading a page: https://i.stack.imgur.com/gRQKj.png Is there a way to customize the settings of the Chrome ...

Tips for obtaining the dynamically loaded HTML content of a webpage

I am currently attempting to extract content from a website. Despite successfully obtaining the HTML of the main page using nodejs, I have encountered a challenge due to dynamic generation of the page. It seems that resources are being requested from exter ...