Guide 3.2: Developer Guide

Using SdashAPI with React Native

React Native allows you to write JavaScript that compiles down to native iOS and Android applications. Because React Native supports the standard Fetch API, fetching data from SdashAPI is almost identical to standard React, though you will render native <View> and <Text> components instead of HTML divs.

Fetching Data in a Native Environment

3.2.1

Here is a functional React Native component that fetches a question and renders a tappable list of options using TouchableOpacity.

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

const MobileQuizScreen = () => {
  const [questionData, setQuestionData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchApi = async () => {
      try {
        const response = await fetch('https://sdashapi.com/api/v1/q?type=utme&subject=physics', {
          headers: { 'AccessToken': 'YOUR_API_KEY_HERE' }
        });
        const json = await response.json();
        if (json.status === 200) {
          setQuestionData(json.data);
        }
      } catch (error) {
        console.error('API Error', error);
      } finally {
        setLoading(false);
      }
    };
    fetchApi();
  }, []);

  if (loading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator size="large" color="#2563eb" />
      </View>
    );
  }

  if (!questionData) return <View style={styles.center}><Text>Error loading...</Text></View>;

  return (
    <View style={styles.container}>
      <Text style={styles.questionText}>{questionData.question}</Text>
      
      {Object.entries(questionData.option).map(([key, value]) => {
        if (!value) return null;
        return (
          <TouchableOpacity key={key} style={styles.optionBtn}>
            <Text style={styles.optionText}>
              {key.toUpperCase()}. {value}
            </Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#f8fafc' },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  questionText: { fontSize: 18, fontWeight: 'bold', marginBottom: 20, color: '#0f172a' },
  optionBtn: { padding: 15, backgroundColor: '#fff', borderRadius: 8, marginBottom: 10, borderWidth: 1, borderColor: '#e2e8f0' },
  optionText: { fontSize: 16, color: '#334155' }
});

export default MobileQuizScreen;

Prefer Dart?

Next, we will look at how to build mobile interfaces using Google's Flutter framework.

Next Guide: Using Flutter →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?