Home > Blockchain >  how to deconstruct an object that is coming from useFetch?
how to deconstruct an object that is coming from useFetch?

Time:12-19

a react document about my question

import { useParams } from 'react-router-dom';
import { useFetch } from '../../hooks/useFetch';
import { URL } from '../../util/fetchURL';

export default function Recipe() {
  const { id } = useParams();

  const { data: recipe, isPending, error } = useFetch(`${URL}/${id}`);

  return (
    <div className='recipe'>
      {error && <p className='error'>{error}</p>}
      {isPending && <p className='loading'>loding...</p>}

      {recipe && (
        <>
          <h2 className='page-title'>{title}</h2>
          <p>Takes {cookingTime} to cook.</p>
          <ul>
            {ingredients.map((ing) => (
              <li key={ing}>{ing}</li>
            ))}
          </ul>
          <p className='method'>{method}</p>
        </>
      )}
    </div>
  );
}

so basically, I've got a custom useFetch hook that some data and some other stuff returning.

in 'recipe' variable, I have an object consisting of ''title, cookingTime, method' etc.

my question is, how to deconstruct this recipe object into:

  const {title, cookingTime, method, ingredients} = recipe

this code won't work if I put it below the useFetch hook because at first, it will be null before going into the useEffect hook which is inside the useFetch, any idea?

CodePudding user response:

I'd make another component, maybe call it RecipeData, that you pass down the recipe from the fetch result as a prop, and only render if the data exists.

const RecipeData = ({ recipe }) => {
  const {title, cookingTime, method, ingredients} = recipe;
  return (<>
    <h2 className='page-title'>{title}</h2>
    <p>Takes {cookingTime} to cook.</p>
    ...
  );
};
export default function Recipe() {
  const { id } = useParams();

  const { data: recipe, isPending, error } = useFetch(`${URL}/${id}`);
  return (
    <div className='recipe'>
      {error && <p className='error'>{error}</p>}
      {isPending && <p className='loading'>loding...</p>}

      {recipe && <RecipeData recipe={recipe} />}
    </div>
  );
}
  • Related