create a react native component that fetches data from an api and displays it in typescript

Here's an example of a React Native component that fetches data from an API and displays it using TypeScript.

index.ts
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';

interface Props {
  apiUrl: string;
}

interface User {
  id: number;
  name: string;
  email: string;
}

const UserList: React.FC<Props> = ({ apiUrl }) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(apiUrl)
      .then(response => response.json())
      .then(data => {
        setUsers(data);
        setLoading(false);
      });
  }, [apiUrl]);

  if (loading) {
    return (
      <View style={styles.container}>
        <Text>Loading...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {users.map(user => (
        <View key={user.id} style={styles.user}>
          <Text style={styles.userName}>{user.name}</Text>
          <Text style={styles.userEmail}>{user.email}</Text>
        </View>
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    alignItems: 'center',
    justifyContent: 'center',
  },
  user: {
    marginBottom: 12,
  },
  userName: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  userEmail: {
    fontSize: 14,
  },
});

export default UserList;
1267 chars
67 lines

In this example, we define a Props interface that accepts an apiUrl string. We then define a User interface for the expected data we'll fetch from the API.

We declare some state variables using the useState hook; users will hold the fetched data, and loading will handle whether or not we display a "Loading" message.

In the useEffect hook, we fetch data from the passed apiUrl prop using the fetch function. We then convert the response to JSON and set the users state with the response data. Finally, we set the loading state to false.

If loading is truthy, we render a "Loading" message. Otherwise, we map through the users state and display the name and email address of each user.

We also define some basic styles using the StyleSheet.create function.

This component can be used by passing in an API URL as the apiUrl prop.

gistlibby LogSnag