Skip to content

Instantly share code, notes, and snippets.

@hamza4600
Last active November 24, 2022 19:24
Show Gist options
  • Save hamza4600/5fc3a05a6bc0d71a6b2bfa50f9579974 to your computer and use it in GitHub Desktop.
Save hamza4600/5fc3a05a6bc0d71a6b2bfa50f9579974 to your computer and use it in GitHub Desktop.
Custom Hook to get Data from Api and Show Response in React
import { useState } from "react";
function useData(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [localData, setLocalData] = useState(
JSON.parse(localStorage.getItem("data")) || []
);
if (!url) return;
const callApi = async () => {
try {
setLoading(true);
const req = await fetch(url);
const data = await req.json();
if (!req.ok) {
setError("Something went wrong");
setLoading(false);
return;
}
setData(data);
setLocalData(data);
localStorage.setItem("data", JSON.stringify(data));
setLoading(false);
} catch (err) {
setError(err);
setLoading(false);
}
}
const removeData = () => {
setData([]);
localStorage.removeItem("data");
setLocalData([]);
setError(null);
}
return { data, loading, error, callApi, localData, removeData };
}
@hamza4600
Copy link
Author

get Data from endpoint set it to local storage and other attributes you can use it in app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment