skip to Main Content
  const [featureRatings, setFeatureRatings] = useState(() =>
    product.features.map((feature: { category: any }) => ({
      category: feature.category,
      rating: 0, // Default rating value
    }))
  );
const [processLifecycleRatings, setProcessLifecycleRatings] = useState(
 

enter image description here

help me to figure out what is going on here

2

Answers


  1. The error TypeError: product.features.map is not a function indicates that product.features is not an array, and therefore, the .map() method cannot be called on it. This can happen if product.features is undefined, null, or any value that isn’t an array (like an object or a string).

    To fix this issue, you should ensure that product.features is an array before calling .map().

    Check if product.features is an array before calling .map():

       const [featureRatings, setFeatureRatings] = useState(() =>
        Array.isArray(product.features)
            ? product.features.map((feature: { category: any }) => ({
                category: feature.category,
                rating: 0, // Default rating value
              }))
            : [] // If not an array, use an empty array as a fallback
        );
    

    Conditional Rendering or Default Props: You can also use conditional rendering or default props to ensure that product.features is always an array before using .map():

    const product = {
    features: product.features || [] // Fallback to empty array if features is undefined
    };

    const [featureRatings, setFeatureRatings] = useState(() =>
      product.features.map((feature: { category: any }) => ({
        category: feature.category,
        rating: 0,
      }))
    );
    
    Login or Signup to reply.
  2. The time your useStates callback is running products.features would be undefined. So you are not able to map it.
    You could use optional chaining with a fallback empty array value.

    You could use useEffect and wait till products.features is an array.

    But would like to see more of your code before I give you a good solution

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search