Skip to content

Commit

Permalink
Build a Custom Hook: useFetch
Browse files Browse the repository at this point in the history
  • Loading branch information
15Dkatz committed Oct 25, 2022
1 parent 05700a3 commit d8499b7
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 22 deletions.
17 changes: 3 additions & 14 deletions react-hooks/home/src/Joke.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
import React, { useEffect, useState } from 'react';
import React from 'react';
import { useFetch } from './hooks';

function Joke() {
const [joke, setJoke] = useState({});

useEffect(() => {
fetch('https://official-joke-api.appspot.com/jokes/random')
.then(response => response.json())
.then(json => {
console.log('joke json', json);

setJoke(json);
});
}, []);

const { setup, punchline } = joke;
const { setup, punchline } = useFetch('https://official-joke-api.appspot.com/jokes/random', {});

return (
<div>
Expand Down
11 changes: 3 additions & 8 deletions react-hooks/home/src/Stories.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import React, { useState, useEffect } from 'react';
import React from 'react';
import { useFetch } from './hooks';

function Stories() {
const [stories, setStories] = useState([]);

useEffect(() => {
fetch('https://news-proxy-230704.appspot.com/topstories')
.then(response => response.json())
.then(json => setStories(json));
}, []);
const stories = useFetch('https://news-proxy-230704.appspot.com/topstories', []);

return (
<div className='Stories'>
Expand Down
13 changes: 13 additions & 0 deletions react-hooks/home/src/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useEffect, useState } from 'react';

export const useFetch = (url, initialValue) => {
const [result, setResult] = useState(initialValue);

useEffect(() => {
fetch(url)
.then(response => response.json())
.then(json => setResult(json));
}, []);

return result;
}

0 comments on commit d8499b7

Please sign in to comment.