Home > OS >  React native: API not loading
React native: API not loading

Time:03-18

Trying to do a simple API call example in react native, however, when running the app, only the "Loading..." message is displayed on screen and will no display the API.

import React, { useEffect, useState } from 'react';
import {StyleSheet, Flatlist, View, Text} from "react-native";

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData]=useState([]);
  console.log(data);

  useEffect(() => {

    fetch('https://raw.githubusercontent.com/adhithiravi/React-Hooks-Examples/master/testAPI.json')
    .then((response) => response.json())
    .then((json) => setData(json))
    .catch((error) => console.log(error))
    .finally(() => setLoading(false));



  }, []);
  return(
    <View style={{flex:1,padding:24}}>
    {isLoading ? <Text>Loading...</Text>:
    (<View style={{flex:1, flexDirection: 'column',justifyContent: 'space-between'}}>
      <Text style={{fontSize:18,color:'green', textAlign:'center'}}>{data.title}</Text>
      <Text style={{fontSize:14, color:'green', textAlign:'center',paddingBottom:10}}>Heading:</Text>

      <FlatList
              data={data.articles}
              keyExtractor={({id},index) =>id}
              renderitem={({item}) => (
                <Text>{item.id '.'  item.title}</Text>
              )}
              />
              </View>
    )}
    </View>
  );
              };

I tried checking through the code and can't see any issues. There are no error which so up in the console either.

CodePudding user response:

There are some typo mistakes, I resolved as below:

import React, { useEffect, useState } from "react";
import { StyleSheet, FlatList, View, Text } from "react-native";

const App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  console.log(data);

  useEffect(() => {
    fetch(
      "https://raw.githubusercontent.com/adhithiravi/React-Hooks-Examples/master/testAPI.json"
    )
      .then((response) => response.json())
      .then((json) => {
        console.log(json)
        setData(json)})
      .catch((error) => console.log(error))
      .finally(() => setLoading(false));
  }, []);
  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? (
        <Text>Loading...</Text>
      ) : (
        <View
          style={{
            flex: 1,
            flexDirection: "column",
            justifyContent: "space-between",
          }}
        >
          <Text style={{ fontSize: 18, color: "green", textAlign: "center" }}>
            {data.title}
          </Text>
          <Text
            style={{
              fontSize: 14,
              color: "green",
              textAlign: "center",
              paddingBottom: 10,
            }}
          >
            Heading:
          </Text>

          <FlatList
            data={data.articles || []}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => <Text>{item.id   "."   item.title}</Text>}
          />
        </View>
      )}
    </View>
  );
};

export default App;


Demo Preview - https://snack.expo.dev/@emmbyiringiro/laughing-donut

CodePudding user response:

You have some small typos. Fix them and you'll be alright.

Original

import {StyleSheet, Flatlist, View, Text} from "react-native";

here it should be imported as FlatList. Notice the capital L.

Fixed

import {StyleSheet, FlatList, View, Text} from "react-native";

Original

renderitem={({item}) => (
                <Text>{item.id '.'  item.title}</Text>
              )}

here in the first line, it should be renderItem with a capital I.

{"index": 1, "item": {"id": "2", "title": "GraphQL APIs FAQ"}, "separators": {"highlight": [Function highlight], "unhighlight": [Function unhighlight], "updateProps": [Function updateProps]}}
{"index": 2, "item": {"id": "3", "title": "JavaScript 101"}, "separators": {"highlight": [Function highlight], "unhighlight": [Function unhighlight], "updateProps": [Function updateProps]}}

Notice how the incoming data is structured.The required data is inside a separate object called "item" inside a single "item". So to access them you should do as follows.

Fixed

renderItem={item => (
                  <Text>{item.item.id '.'  item.item.title}</Text>
                )}

you could also improve this line

keyExtractor={({id},index) =>id}

with

keyExtractor={item => item.id}

It won't do anything visually. But lesser code.

  • Related