ReactNative setState JSON object

Related searches

I have a ReactNative app that has a getUserSession function that returns a JSON object. I am wanting to call this function and then setState to the result of the callback from getUserSession.

class AppContainer extends Component{
 constructor(props){
 super(props);

   this.state = {
      selectedTab: 'profile',
   }
}

componentDidMount(){
    this.fetchData();

    this.setState({
       loggedIn: true,
    });
}

fetchData(){
    userService.getUserSessionData(function(result){
      // Console log function displays correct result
      console.log(result);
      this.setState({
        user: JSON.stringify(result),
      });
    })
}

render() {
    let currentUser = this.state.user;

   return (
     <TabBarIOS style={Theme.appContainer}>
       <TabBarIOS.Item
         title="Profile"
         selected={this.state.selectedTab == "profile"}
         <NavigatorIOS
           initialRoute={{
             title: 'Profile',
             component: Profile,
             passProps: {data: currentUser}
           }} />
       </TabBarIOS.Item>

     </TabBarIOS>
   );
  }
 };

 module.exports = AppContainer;

The console.log function in fetchData presents the expected behaviour and displays exactly what I am wanting, however on the next line it doesn't setState correctly.

When passing the state through using PassProps on NavigatorIOS, the child component 'Profile' doesn't receive the props and returns an 'undefined'.

I have tried to JSON.stringify() the result because I thought that setState would allow a string of the JSON, however this doesn't work either


First define initial state like

this.state = {
      user: '',
   }

then on calling fetchData function

fetchData(){
     let me = this;    
    userService.getUserSessionData(function(result){
      // Console log function displays correct result
      console.log(result);
      me.setState({                    // scope of this doesn't exist in promise based functions
        user: JSON.stringify(result),
      });
    })
}

this will work.

Instead of this ,please do some correction

render() {
    const {user, selectedTab} = this.state; // destructuring ,good practice. 
   return (
     <TabBarIOS style={Theme.appContainer}>
       <TabBarIOS.Item
         title="Profile"
         selected={selectedTab == "profile"}
         <NavigatorIOS
           initialRoute={{
             title: 'Profile',
             component: Profile,
             passProps: {data: user}
           }} />
       </TabBarIOS.Item>

     </TabBarIOS>
   );
  }
 };

 module.exports = AppContainer;

Storing JSON data in React with setState - Brett Celestre, setState() method inside of our ajax call to store our data. We do this by using this​.setState and then pass an object with our state name as the key and for the  React setState() with prevState and Object Spread Operator There are some gotchas with React’s setState(). For example, state updates may be asynchronous : React sometimes batches multiple setState() calls for performance reasons. Make sure to set state correctly and to use the latest state.


I think this is no longer pointing to the correct reference. Try rewriting the function like this, using the fat arrow syntax available in ES6:

fetchData(){
  userService.getUserSessionData((result) => {
    console.log(result);
    this.setState({
      user: JSON.stringify(result),
    });
  })
}

Reactjs, I am working on the react recipe box challenge and have a question regarding Reactjs - Using setState to update a single property on an object let recipesCopy = JSON.parse(JSON.stringify(this.state.recipes)) //make  Object.assign(obj mutates the current state object which is an anti-pattern in React. Object.assign({}, obj would correctly create a new object. – Emile Bergeron Mar 6 at 19:40


How about trying to set a default value on your state, i.e

this.state = {
  user: '',
  loggedIn: false,
  etc:'',
}

Updating properties of an object in React state, Despite that, as known by most of you, setState is asynchronous, and React is smart enough to handle multiple setState in one action: You will  To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of condition=true, return the new object with updated value, else same object. let key = 2; this.setState(prevState => ({ todoItems: prevState.todoItems.map( el => el.key === key? { el, status: 'done' }: el ) }))


How to initialize state to Receive object json data? : reactjs, setState({ airportStatus: JSON.parse(response.data) }) Introducing react-cool-​inview - React hook to monitor an element enters or leaves the viewport. To join, all you need is some (demonstratable) understanding of JS, HTML, and CSS​. Ahh sorry! Values is the imported json file. and myval was a typo, it's "person". I've updated to reflect that. – Ash Aug 11 '16 at 2:32


AJAX and APIs – React, This is so you can use setState to update your component when the data is retrieved. The example API returns a JSON object like this: { "items": [ { "id": 1  Unlike Redux, React is smart that you don’t need to always put the final outcome of the new state in the setState function. You can expect property b remains while you only put a in setState. While in Redux, if you only return a in the new state, don’t expect you can find b anymore. That means, you need to take care of the entire state object in Redux. That also means, you need to put all the specific logic in one place and can’t delegate to multiple handlers.


Name Type Required Description; keys: Array: Yes: Array of key for the items to get. callback?(errors: ?Array, result: ?Array<Array >) => void: No: Function that will be called with a key-value array of the results, plus an array of any key-specific errors found.