Day 6 π - Learning ReactJS: Calling APIs & Creating Context Providers | Distriator Feature Update
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
- π Day One: Fresh React app + AIOHA integration!
- π§ Day Two: Routing drama & rebellious NavBar π€
- π οΈ Day Three: Fixed Layouts, Routing & AIOHA π₯
- π§ Day Four: useState, useEffect, and .env headaches π
- π§Ή Day Five: Path Aliases to clean up relative path spaghetti π
π‘ API Calling β The Right Way
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
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!
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 πͺ
β
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
- I asked ChatGPT/AI to help optimize this post to make it more readable and viewer-friendly.
- Here is the link where you can find both original content & improvements made by AI
- https://chatgpt.com/share/688ad30f-5d64-8000-9f97-b26950da7bd6
π My Contributions to β¦οΈ Hive Ecosystem
| Contribution | To | Hive | Ecosystem |
|---|---|---|---|
| Hive Witness Node | Hive API Node (in progress) | 3Speak Video Encoder Node Operator (highest number of nodes) | 3Speak Mobile App Developer |
| 3Speak Podcast App Developer | 3Speak Shorts App Developer | 3Speak Support & Maintenance Team | Distriator Developer |
| CheckinWithXYZ | Hive Inbox | HiFind | Hive Donate App |
| Contributed to HiveAuth Mobile App | Ecency β 3Speak Integration | Ecency β InLeo Integration | Ecency β Actifit Integration |
| Hive Stats App | Vote for Witness App | HiveFlutterKit | New 3Speak App |
π Support Back
β€οΈ Appreciate my work? Consider supporting @threespeak &
@sagarkothari88! β€οΈ
| Vote | For | Witness |
|---|---|---|
| sagarkothari88 | ||
| threespeak |
Leave Day 6 π - Learning ReactJS: Calling APIs & Creating Context Providers | Distriator Feature Update to:
Read more #hive posts
Best Posts From Sagar Kothari
We have not curated any of sagarkothari88's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Sagar Kothari
- HiveSuite Dev Update: Introducing Word Finder β A Daily Hive Word Puzzle
- HiveSuite Dev Update: Smarter Uploads, Posting Authority Management & Enhanced Media Viewing
- HiveSuite Dev Updates: Today was a slow day. Less updates
- HiveSuite Dev Update: Advanced Media Handling, Profile Enhancements & Upload Experience Improvements
- HiveReactKit Development Update: Improved Translation Engine, Version History & Advanced Post Inspection
- HiveSuite Development Update: Stable Hive Node Control, Advanced Media Viewer & Exchange Directory
- HiveSuite Dev Update: Exchanges Directory & Media Experience
- HiveReactKit Dev Update: Translation Controls & Wallet Trxns UX
- HiveSuite Dev Update: Persistent Nav & Scroll Restoration
- HiveSuite Dev Update: Market Prices Popup & Persistent Nav Ex