score:1
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.
Source: stackoverflow.com
Related Query
- React - write and read nested objects in state
- React state comparison with objects and nested arrays
- React - nested objects and useState is mutating original state
- How to set and access values of nested array objects in React state using useState hook?
- How to write and read component state in React?
- React State update a nested array with objects based on the id when iterated
- Handling state and arrays of objects in React
- Write nested objects in this.state in react js
- Taking React State (object of objects(example inside)) and getting an array of objects to map() for component rendering
- Nested form state and one onChange function in React
- Using nested objects in redux initial state and reducers
- Using nested objects with Flow in React state
- How to pass down state and handlers in nested React components
- Update react State array of nested objects
- React - using nested objects as state with hooks to fill form data
- Firebase + react : read document in auth state changed and add it to context
- Finding values or objects in a json file with nested objects and passing the result object to child in Javascript and react
- how to update nested state array and then return the entire array react
- Update state dynamically with nested levels of objects and array
- TypeError: Cannot read property 'map' of undefined in ReactJs AND Error: Objects are not valid as a React child
- Updating nested state in objects through an input element in React
- How to copy nested state between objects in React
- React looping and creating new array with nested objects
- Storing nested objects in React State
- React Hooks: how to properly map an array with nested arrays and objects inside a select element?(new coder)
- React Cannot read property 'bind' of undefined from constructor/componentDidMount and Unable to set state on unmounted component
- React event target value from jsx element does not get bind to state and json array (Type error cannot read the properties of undefined )
- How do you use state variables to make a nested drag and drop in React / Kanban board not working in React
- How to display and update deep nested values in React state
- Does React update all the variables and objects dependent on Component State if the state get updated?
More Query from same tag
- React json Data inside value check validation
- Sending a JWT in header with Apollo/GraphQL
- ReactJS: doing calculations to setState, and updating
- Stripe Elements, input validation upon form submit
- How to get URL query string on Next.js static site generation?
- Logo does not change on scrolling using React
- React: Understanding import statement
- Customize layout of AmplifySignOut
- How can "False positive" coverage in React Jest tests be avoided
- With useEffect, how can I skip applying an effect upon the initial render?
- How to use call method from Model to controller in Rails
- Why there is no physical client/build folder when i run nodejs server with react app as frontend
- editing slick-list class in react slick slider
- React functional components in Array.map are always rerendering when getting passed a function as props
- firebase notification events not working in service worker (notifcationclose, notificationclick)
- Why is Next.JS automatically removing CSS during production build?
- I don’t know how best to put new data into a reducer
- Delete an object property with Object.assign()
- React table re-renders, losing focus when input text in table cell
- Uncaught SyntaxError: Unexpected token '<' firebase-app.js.1, firebase-analytics.js.1 & init.js.1 using react & firebase
- npm: import from outside the src folder
- react-redux: dispatch action from reducer
- Focus the last element of a map html rendering
- useState not updating state object after fetching data from API endpoint
- How do you remove a class from elements inside a component in React.JS when clicking outside given component?
- Link tag not triggering onSubmit when clicking on the form's submit button
- React filter items with dropdown
- Prevent data refresh in React-Query by data hash matching
- componentDidUpdate load API infinity times
- Cannot read properties of undefined (reading 'preventDefault')