Home > database >  React Hooks: How can I use a hook to map an array from a dumb component
React Hooks: How can I use a hook to map an array from a dumb component

Time:04-22

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?

CodePudding user response:

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?

  • Related