Last active
November 24, 2022 19:24
-
-
Save hamza4600/5fc3a05a6bc0d71a6b2bfa50f9579974 to your computer and use it in GitHub Desktop.
Custom Hook to get Data from Api and Show Response in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
get Data from endpoint set it to local storage and other attributes you can use it in app