Guide 3.1: Developer Guide

Using SdashAPI with React

React is the most popular frontend library for building interactive user interfaces. When integrating SdashAPI with React, you need to carefully manage network requests alongside component lifecycles using hooks like useEffect and useState.

Managing State and Fetching Data

3.1.1

In this example, we will create a simple QuestionCard component that fetches a WAEC English question when it mounts to the DOM. We will handle the loading state, error states, and the final rendering of the question options.

import React, { useState, useEffect } from 'react';

const QuestionCard = () => {
  const [question, setQuestion] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchQuestion = async () => {
      try {
        const res = await fetch('https://sdashapi.com/api/v1/q?type=wassce&subject=english', {
          headers: {
            'AccessToken': 'YOUR_API_KEY_HERE' 
            // NOTE: In production, fetch from your own backend proxy!
          }
        });
        const json = await res.json();
        
        if (json.status === 200) {
          setQuestion(json.data);
        } else {
          setError('Failed to load question from API.');
        }
      } catch (err) {
        setError('A network error occurred.');
      } finally {
        setLoading(false);
      }
    };

    fetchQuestion();
  }, []); // Empty dependency array ensures this runs only once on mount

  if (loading) return <div>Loading question...</div>;
  if (error) return <div style={{ color: 'red' }}>{error}</div>;
  if (!question) return null;

  return (
    <div className="card p-6 border rounded shadow-sm">
      <h2 className="text-lg font-bold mb-4">{question.question}</h2>
      <div className="space-y-2">
        {Object.entries(question.option).map(([key, value]) => {
          if (!value) return null;
          return (
            <div key={key} className="p-3 border rounded hover:bg-gray-50 cursor-pointer">
              <strong>{key.toUpperCase()}.</strong> {value}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default QuestionCard;

Building for mobile?

Next, we will adapt this React code for iOS and Android using React Native.

Next Guide: Using React Native →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?