Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 83 additions & 93 deletions src/useDataApiHook-example/index.js
Original file line number Diff line number Diff line change
@@ -1,112 +1,102 @@
import React, {
Fragment,
useState,
useEffect,
useReducer,
} from 'react';
import React, { Fragment, useState, useEffect, useReducer } from 'react';
import axios from 'axios';

const dataFetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_INIT':
return { ...state, isLoading: true, isError: false };
case 'FETCH_SUCCESS':
return {
...state,
isLoading: false,
isError: false,
data: action.payload,
};
case 'FETCH_FAILURE':
return {
...state,
isLoading: false,
isError: true,
};
default:
throw new Error();
}
switch (action.type) {
case 'FETCH_INIT':
return { ...state, isLoading: true, isError: false };
case 'FETCH_SUCCESS':
return {
...state,
isLoading: false,
isError: false,
data: action.payload
};
case 'FETCH_FAILURE':
return {
...state,
isLoading: false,
isError: true
};
default:
throw new Error();
}
};

const useDataApi = (initialUrl, initialData) => {
const [url, setUrl] = useState(initialUrl);
const useDataApi = (initialData, initialUrl = 'http://hn.algolia.com/api/v1/search?query=redux') => {
const [ url, setUrl ] = useState(initialUrl);

const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
data: initialData,
});
const [ state, dispatch ] = useReducer(dataFetchReducer, {
// passing isLoading and isError property is redundant here
data: initialData
});

useEffect(() => {
let didCancel = false;
useEffect(
() => {
let didCancel = false;

const fetchData = async () => {
dispatch({ type: 'FETCH_INIT' });
const fetchData = async () => {
dispatch({ type: 'FETCH_INIT' });

try {
const result = await axios(url);
try {
const result = await axios(url);

if (!didCancel) {
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
}
} catch (error) {
if (!didCancel) {
dispatch({ type: 'FETCH_FAILURE' });
}
}
};
if (!didCancel) {
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
}
} catch (error) {
if (!didCancel) {
dispatch({ type: 'FETCH_FAILURE' });
}
}
};

fetchData();
fetchData();

return () => {
didCancel = true;
};
}, [url]);
return () => {
didCancel = true;
};
},
[ url ]
);

return [state, setUrl];
return [ state, setUrl ];
};

function App() {
const [query, setQuery] = useState('redux');
const [{ data, isLoading, isError }, doFetch] = useDataApi(
'http://hn.algolia.com/api/v1/search?query=redux',
{ hits: [] },
);

return (
<Fragment>
<form
onSubmit={event => {
doFetch(
`http://hn.algolia.com/api/v1/search?query=${query}`,
);

event.preventDefault();
}}
>
<input
type="text"
value={query}
onChange={event => setQuery(event.target.value)}
/>
<button type="submit">Search</button>
</form>

{isError && <div>Something went wrong ...</div>}

{isLoading ? (
<div>Loading ...</div>
) : (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
)}
</Fragment>
);
const [ query, setQuery ] = useState('redux');
// Now our Custom hookAPI resemble more like native hook
const [ result, setUrl ] = useDataApi({ hits: [] });
const { data, isLoading, isError } = result;

return (
<Fragment>
<form
onSubmit={(event) => {
setUrl(`http://hn.algolia.com/api/v1/search?query=${query}`);

event.preventDefault();
}}
>
<input type="text" value={query} onChange={(event) => setQuery(event.target.value)} />
<button type="submit">Search</button>
</form>

{isError && <div style={{ color: 'red' }}>Something went wrong ...</div>}

{isLoading ? (
<div>Loading ...</div>
) : (
<ul>
{data.hits.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
)}
</Fragment>
);
}

export default App;