简体   繁体   中英

React Native is Not fetching the latest data from API call

I sicerely Apologies if this has been asked before. I am a bit new to react native and react in general.

my react nativee code is not fetcing the latest data see the code for the list component below I would deeply appreciate it if you can tell me why this is happening and how to make it pick the latest data

import React, { Component } from "react";
import {
  FlatList,
  Text,
  View,
  StyleSheet,
  ScrollView,
  ActivityIndicator
} from "react-native";
import Constants from "expo-constants";
import { createStackNavigator } from "@react-navigation/stack";
import { toCommaAmount } from "./utilities";

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={ExpenseList} />
      <Stack.Screen name="NewTransaction" component={ExpenseForm} />
    </Stack.Navigator>
  );
}

function Item({ title }) {
  return (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
}

class ExpenseList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    };
  }

  componentDidMount() {
    return fetch("https://example.com/expense/api/get_all.php")
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          isLoading: false,
          dataSource: responseJson.items
        });
      })

      .catch(error => console.log(error));
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator />
        </View>
      );
    } else {
      let myExpenses = this.state.dataSource.map((val, key) => {
        return (
          <View key={key} style={styles.item}>
            <Text>
              {val.title} {toCommaAmount(val.amount)}
            </Text>
            <Text>{val.date_time}</Text>
          </View>
        );
      });

      return <View style={styles.container}>{myExpenses}</View>;
    }
  }
}

export default ExpenseList;

ComponentDidMount is a void function. I assume you have this problem because you try to return the result of the fetch execution.

Can you remove your api call out of componentDidMount(), because it gets invoked only once. Rename it to getRealData() and attach it to a button click. So every click on button will being up latest data from backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM