Home > Software engineering >  React native view fails to refresh after the state variable updated
React native view fails to refresh after the state variable updated

Time:10-03

I am new to React and have difficulties on refresh data in the . I am expecting that the view should shows

"Hello World! Shyam"

But it only shows "Hellow World".

My code:

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class WhatsDes extends Component {
  constructor(props) {
                super(props);
                this.state = {name:'', email:''};
            }
  
  
  render() {
      console.log('Start render ....');
      const url = 'http://192.168.1.13:8091/employees';  
      fetch(url)
        .then(response => response.json())
        .then(responseJson => {
          console.log('ok 1: '  JSON.stringify(responseJson));
          console.log('ok 2: ' responseJson[0].name);
          this.state.name = responseJson[0].name;
        })
        .catch(error => {
          console.log('error'  error);
        });  
    console.log('Show view ...' );
    console.log('this.state.name ...'   this.state.name);
    return (
      
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Hello, world ! {this.state.name}</Text>
      </View>
    );
  }
}

Log output:

LOG  Running "WhatsDes" with {"rootTag":201}
 LOG  Start render ....
 LOG  Show view ...
 LOG  this.state.name ...
 LOG  ok 1: [{"name":"Shyam","email":"[email protected]"},{"name":"Bob","email":"[email protected]"},{"name":"Jai","email":"[email protected]"}]
 LOG  ok 2: Shyam

CodePudding user response:

Do not mutate state. If you want to update state, use the setState method.

change your state update,

this.state.name = responseJson[0].name;

to

this.setState({name: responseJson[0].name});

Read more about setState at https://reactjs.org/docs/react-component.html#setstate

Edit: Upon close inspection, noticed a few more no no in your code.

You are doing all these actions inside of the render function. This is not the correct way of doing it.

Move your API calls to componentDidMount function, which will only be executed on your component mount. Doing it in render as you are doing now will repeatedly call that function on each render and will throw error Max callstack exceeded.

Change your code to,

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class WhatsDes extends Component {
  
  constructor(props) {
    super(props);
    this.state = {name:'', email:''};
  }
   
  componentDidMount() {
    const url = 'http://192.168.1.13:8091/employees';  
    fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        this.setState({ name: responseJson[0].name });
      })
      .catch(error => {
        console.log('error'  error);
    });
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Hello, world ! {this.state.name}</Text>
      </View>
    );
  }
}

perhaps a good idea to look through the Life cycle events - React

  • Related