Skip to content

Instantly share code, notes, and snippets.

View simicd's full-sized avatar

Dejan Simic simicd

View GitHub Profile
// DogImage.tsx
import React, { FC, useState, useEffect } from "react";
export const DogImage: FC = () => {
type DogImageType = { message: string; status: string };
const [data, setData] = useState<DogImageType>();
useEffect(() => {
// Define asynchronous function - since useEffect hook can't handle async directly,
// useFetch.ts
import { useState, useEffect } from "react";
interface RequestProps {
url: RequestInfo;
init?: RequestInit;
}
type DogImageType = { message: string; status: string };
// useFetch.ts
// ...
export const useFetch = ({ url, init }: RequestProps) => {
// Response state
const [data, setData] = useState<DogImageType>();
useEffect(() => {
// Define asynchronous function
//DogImage.tsx
import React, { FC } from "react";
import { useFetch } from "./useFetch";
export const DogImage: FC = () => {
const data = useFetch({ url: "https://dog.ceo/api/breed/beagle/images/random"})
return <>{data ? <img src={data.message} alt="dog"></img> : <div>Loading</div>}</>;
};
// useFetch.ts
// ...
export const useFetch = ({ url, init }: RequestProps) => {
// Response state
const [data, setData] = useState<DogImageType>();
useEffect(() => {
// Define asynchronous function
// DogImage.tsx
import React, { FC } from "react";
import { useFetch } from "./useFetch";
export const DogImage: FC = () => {
const data = useFetch({ url: "https://dog.ceo/api/breed/beagle/images/random", init: {}})
return <>{data ? <img src={data.message} alt="dog"></img> : <div>Loading</div>}</>;
};
// useFetch.ts
// ..
export const useFetch = ({ url, init }: RequestProps) => {
// Response state
// ..
useEffect(() => {
// ...
// useFetch.ts
import { useState, useEffect } from "react";
// ..
export const useFetch = ({ url, init }: RequestProps) => {
// ...
// Turn objects into strings for useCallback & useEffect dependencies
// DogImage.tsx
import React, { FC } from "react";
import { useFetch, DogImageType } from "./useFetch";
export const DogImage: FC = () => {
const data = useFetch({
url: "https://dog.ceo/api/breed/beagle/images/random",
processData: (data) => data as DogImageType,
});
// useFetch.ts
import { useState, useEffect } from "react";
interface RequestProps {
url: RequestInfo;
init?: RequestInit;
processData?: (data: any) => DogImageType
}
export type DogImageType = { message: string; status: string };