Design comparison
Solution retrospective
i builld this challange with react+tailwindcss
Community feedback
- @RubenSmnPosted almost 2 years ago
Hi Annang, great work on this challenge. I had a look at the code and found some things you could improve on.
Instead of a
Api
component a more recommended/best practice in React is by using a custom hook.// api const useApi = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { setLoading(true); axios .get(url) .then((response) => { setData(response.data); }) .catch((err) => { setError(err); }) .finally(() => { setLoading(false); }); }, [url]); return { data, loading, error }; }; // app const App = () => { const { data, loading, error } = useApi("..."); };
You're currently reloading the whole page when clicking on the button. This is not really the React way of doing things.
A solution for could be to introduce a new return prop from the api hook, a re-fetch function. Here we move the fetch functionality from the
useEffect
into its own function and call the function in theuseEffect
. When returning we can return a new prop calledrefetch
with our new function.const useApi = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); function fetchData() { setLoading(true); axios .get(url) .then((response) => { setData(response.data); }) .catch((err) => { setError(err); }) .finally(() => { setLoading(false); }); } useEffect(() => { fetchData(); }, [url]); return { data, loading, error, refetch: fetchData }; };
The usage of this in the app is as simple as switching the
newDatas
function for therefetch
one.const { data, loading, error, refetch } = useApi( "https://api.adviceslip.com/advice" ); <button onClick={refetch} className=""> ... </button>;
Marked as helpful0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord