I have some hard-coded data in my React app which I would now like to fetch from an API. I would like to preserve the array-like format because that is how the data is used down the road.
My original component:
import moment from 'moment';
const INITIAL_STATE = {
articles:
[
{
title: 'Guerrilla Public Service Redux (2017)',
tag0: 'story',
points: 421,
created_at: moment('2020-05-27T16:05:32.000Z'),
author: 'DerWOK',
},
{
title: 'Build Yourself a Redux',
tag0: 'story',
points: 395,
created_at: moment('2020-05-27T16:05:32.000Z'),
author: 'jdeal',
},
],
};
function Articles (state = INITIAL_STATE) {
return state;
}
export default Articles;
This is how I imagine it to work but what should be in the return() below is a mystery to me:
import moment from 'moment';
function Articles() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch("https://hn.algolia.com/api/v1/search?query=redux")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result.items);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
{items.map(item => (
???)
);
}
}
export default Articles;
Edit: I do have the list component to render the data. I just need to return the data in acceptable form.
Fetch(in your code) is a FunctionalComponent, not a hook. If your problem is the???then you are just trying to render an an array as JSX elements. Please see the suggested duplicate.result.itemmaintains the array-like structure. If you are talking about passing the array structure down to children, you could simply do thisreturn (<SomeComponent itemList={items} />)without usingitems.map