'React Hooks: How can I use a hook to map an array from a dumb component
I have my api call in a React hook, like so:
import { getAllTheBakeries } from './bakeries.api';
export const useBakeryList = () => {
const [bakeries, setBakeries] = React.useState([]);
React.useEffect(() => {
const fetchBakeries = async () => {
try {
const bakeryList = await getAllTheBakeries();
setBakeries(bakeryList.bakeries);
} catch (error) {
console.log(error);
}
};
fetchBakeries();
},[])
return bakeries;
}
And I want to use this returned array in a dumb component like so:
import { useBakeryList } from './bakery-list.hook';
export const BakeryList = () => {
// I can see the returned array in my console
console.log(useBakeryList())
// access the returned array and map it
return(
{bakeries.map((bakery) => (
<p>bakery.name</p>
))}
)
}
What is the proper syntax to access that array returned by the hook?
Solution 1:[1]
import { useBakeryList } from './bakery-list.hook';
export const BakeryList = () => {
let bakeries = useBakeryList();
return(
{bakeries.map((bakery) => (
<p>bakery.name</p>
))}
)
}
Do you want something like that?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alireza tafreshi |
