score:1

Accepted answer

i tried to setstate the actual user but the state results empty, any idea?

it is because your db operation searchresult is asynchronous and javascript does not let the synchronous codes wait until the async code completes.

in your code, if you enable the commented setstate invocation, that code will get executed while the async code is waiting for response.

you need to setstate inside:

searchresults.orderbychild('location').equalto(location).on('value', (snap) => {
    let users = snap.val();
    const profiles = object.keys(users).map((key) => users[key]);
    this.setstate({ users: profiles[0] });
});

whenever you want something to be executed after an async code, put that inside a callback (to the async fn) or use a promise.


what would be the best way to get the data back from the state? how do i loop through objects in the state?

setstate can be asynchronous too. but you will get the new updated state on next render. so inside render() you can access users in the state as this.state.users and perform your operations using it.

update:

componentwillmount(){
    const searchresults = fbappdb.ref('users');
    const location = this.props.location;
    const instrument = this.props.instrument;

    searchresults.orderbychild('location').equalto(location).on('value', (snap) => {
        const users = snap.val();
        const profiles = object.keys(users).map((key) => users[key]);

        // previously we were setting just profiles[0]; but i think you need 
        // the entire list of users as an array to render as search results
        this.setstate({ users: profiles }); // set the whole data to state
    });
}


render(){
    const users = this.state.users || []; // note that this.state.users is an array

    return(
        <row>
            {
              users.length > 0 
              ? users.map((user) => <searchresult user={user} />)
              : null
            }
        </row>
    );
}

score:0

try putting setstate inside the .on(() => ...) just after object.keys(...). it's an asynchronous call to the server, right? i suppose that setstate is called right after the call to the server is made, but before you retrieve any data.


Related Query

More Query from same tag