Day 6 🚀 - Learning ReactJS: Calling APIs & Creating Context Providers | Distriator Feature Update

Words
452
Reading
3 min
Listen
Play
1y

Hey there, Hive community! 👋

Welcome back to my wild ReactJS learning ride 🎢 — and guess what? We’re already on Day 6! If you've missed previous episodes, don't worry. Grab some popcorn 🍿 and catch up below:


📖 ReactJS Journey So Far


📡 API Calling — The Right Way

Fetch Data from server

Using fetch() is easy. But keeping things organized? That’s next-level!

📁 Folder structure:

src/api/
├── business/
│   ├── BusinessApi.tsx  // 👈 Get Business API here

👉 Here’s how I call my Business API:

import type { BusinessDTO } from "@/types/BusinessApiResponse";

export const fetchBusinesses = async () => {
  const response = await fetch("https://some-xyz-server.com/business");
  if (!response.ok) throw new Error("API error");
  const jsonData = await response.json();
  return jsonData as BusinessDTO[];
};

💡 Why a separate file? Because real-world APIs are messy. Headers, body payloads, response transformations — it's cleaner this way! 😎


🧬 DTOs / POJOs / Data Models

Type Script - Type Image

Using TypeScript = getting predictable & strongly typed data 💪

📁 Types live here:

src/types/
├── BusinessApiResponse.tsx  // 👈 All your DTOs in one place

Here’s a sneak peek of my DTO setup:

export interface BusinessDTO {
    distriator?: DistriatorDTO;
    profile?:    ProfileDTO;
    contact?:    ContactDTO;
    location?:   LocationDTO;
    id?:         string;
}

export interface ContactDTO {
    website?: string;
}

export interface DistriatorDTO {
    guides?:             GuideDTO[];
    owner?:              string;
    creator?:            string;
    expiry?:             Date;
    subscriptionStatus?: string;
    paymentMethods?:     string[];
    spendHBDLink?:       string;
}

🧠 Context Providers to the Rescue!

Context Provider Example Image

If businesses are needed everywhere in your app, the answer is simple: Context Provider! 🪄

✅ Step 1: Folder Setup

src/
├── components/
│   └── BusinessList.jsx
├── context/
│   └── BusinessesContext.jsx   // ✅ Lives here

✅ Step 2: Create the Context + Provider

import type { FC, ReactNode } from "react";
import type { BusinessDTO } from "@/types/BusinessApiResponse";
import { fetchBusinesses } from "@/api/BusinessApi";

import React, { createContext, useContext, useState, useEffect } from "react";

const BusinessesContext = createContext();

export const useBusinesses = () => useContext(BusinessesContext);

export const BusinessesProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [businesses, setBusinesses] = useState<BusinessDTO[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    refreshBusinesses();
  }, []);

  const refreshBusinesses = async () => {
    try {
      setLoading(true);
      const data = await fetchBusinesses();
      setBusinesses(data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  return (
    <BusinessesContext.Provider
      value={{ businesses, loading, refreshBusinesses }}
    >
      {children}
    </BusinessesContext.Provider>
  );
};

✅ Step 3: Wrap Your App

import { BusinessesProvider } from "@/context/BusinessesContext";

function App() {
  return (
    <BusinessesProvider>
      <AiohaProvider aioha={aioha}>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<LandingPage />} />
          </Routes>
        </BrowserRouter>
      </AiohaProvider>
    </BusinessesProvider>
  );
}

✅ Step 4: Use It Anywhere!

import React from "react";
import { useBusinesses } from "@/context/BusinessesContext";

function BusinessList() {
  const { businesses, loading } = useBusinesses();

  if (loading) return <p>⏳ Loading businesses...</p>;

  return (
    <div>
      <h2>�� All Businesses</h2>
      <ul>
        {businesses.map((biz) => (
          <li key={biz.id}>�� {biz.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default BusinessList;

And boom 💥 — your business data is now globally available!


🔧 Distriator Project Update

We’ve rolled out a new feature that displays Hive Power of a business! 🐝

This allows users to instantly see how invested a business is in Hive 💪

businesses with hive power

✅ Currently in alpha
🚀 Rolling out to production very soon!


🙌 Wrapping Up

I hope this post helps some curious mind someday 🧠
If you found value in this, consider supporting me in my journey on the Hive blockchain 💖

🙏 Vote me as a Hive Witness
⚡ Let’s build a stronger decentralized world together

Cheers 🥂
More power to Hive community members!
More power to Hive blockchain!



📝 Final Note


🚀 My Contributions to ♦️ Hive Ecosystem

ContributionToHiveEcosystem
Hive Witness NodeHive API Node (in progress)3Speak Video Encoder Node Operator (highest number of nodes)3Speak Mobile App Developer
3Speak Podcast App Developer3Speak Shorts App Developer3Speak Support & Maintenance TeamDistriator Developer
CheckinWithXYZHive InboxHiFindHive Donate App
Contributed to HiveAuth Mobile AppEcency ↔ 3Speak IntegrationEcency ↔ InLeo IntegrationEcency ↔ Actifit Integration
Hive Stats AppVote for Witness AppHiveFlutterKitNew 3Speak App

🙌 Support Back

❤️ Appreciate my work? Consider supporting threespeak@threespeak & sagarkothari88@sagarkothari88! ❤️

VoteForWitness
sagarkothari88sagarkothari88@sagarkothari88
threespeakthreespeak@threespeak

Day 6 🚀 - Learning ReactJS: Calling APIs & Creating Context Provid... | Ecency