Day 6 ๐Ÿš€ - Learning ReactJS: Calling APIs & Creating Context Providers | Distriator Feature Update

in HiveDevs โ€ข 3 months ago

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 & @sagarkothari88! โค๏ธ


Sort: ย 

This post has been manually curated by @bhattg from Indiaunited community. Join us on our Discord Server.

Do you know that you can earn a passive income by delegating to @indiaunited. We share more than 100 % of the curation rewards with the delegators in the form of IUC tokens. HP delegators and IUC token holders also get upto 20% additional vote weight.

Here are some handy links for delegations: 100HP, 250HP, 500HP, 1000HP.

image.png

100% of the rewards from this comment goes to the curator for their manual curation efforts. Please encourage the curator @bhattg by upvoting this comment and support the community by voting the posts made by @indiaunited.

Thank you so much @bhattg & @indiaunited for considering my post for curation.
Have a good day

via Inbox

Congratulations @sagarkothari88! You received a personal badge!

You powered-up at least 10 HIVE on Hive Power Up Day!
Wait until the end of Power Up Day to find out the size of your Power-Bee.
May the Hive Power be with you!

You can view your badges on your board and compare yourself to others in the Ranking

Check out our last posts:

Hive Power Up Month Challenge - July 2025 Winners List
Be ready for the August edition of the Hive Power Up Month!
Hive Power Up Day - August 1st 2025

Congratulations @sagarkothari88! You received a personal badge!

You powered-up at least 1000 HP on Hive Power Up Day and got the biggest Power-Bee!
See you at the next Power Up day to see if you will repeat this feat.
May the Hive Power be with you!

You can view your badges on your board and compare yourself to others in the Ranking

Check out our last posts:

Hive Power Up Month Challenge - July 2025 Winners List
Be ready for the August edition of the Hive Power Up Month!
Hive Power Up Day - August 1st 2025

Okay, I have a doubt rather than going for context hooks and complicating things why don't you go for Redux-Toolkit? Correct me if I'm wrong, but I would like to know it from you.

I am going anywhere possible ๐Ÿคฃ

You're not wrong at all. I am doing direction-less learning.

Good that you've pointed out. I'll do some redux-toolkit learning as well. It's on my list now.

via Inbox

Sure. I got your blogs on my feed and they are interesting to me as I too come from the same background. Now, I'm scrolling through them only and I gotta do the same. For a long time, I have been writing travelling and other random blogs over here.

React isn't my skillset at all. I used to be Swift-iOS app developer - straight 10 years but Apple is innovating backwards.
I tried flutter for over 5 years but it feels dead to me.
Now, I don't know who am I? Where am I heading?

Typical Developers FOMO situation.

fomo

Coding even on Monday ๐Ÿ˜น

via Inbox

Hearing this from someone who has been in the industry for almost 2 decades is already killing. I too sometimes get the FOMO that's why I just keep exploring things, and whichever I feel like I should get it finished I do that from scratch to the advanced.

I feel so bad for myself because I sometimes still code in dead-objective-c programming language in which AI hardly does something well.
AI has killed all experience. Anyone, literally, anyone from market of devs, can do much much better with help of AI.
Forget anyone, even AI is doing better than me, when I ask it to do.

Looks like We have to focus somewhere else.

via Inbox

The best thing to do right now, is to make AI your companion and keep growing. You can't compete with it, you can only use it for yourself and your learning.

Loading...