0

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

import React, { useState } from "react";

import products from '../products'


function RecScreen() {
  const [budget, setBudget] = useState(products);
  const [items, setParts] = useState([]);

  const handleInputChange = (event) => {
    setBudget(event.target.value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    const response = await fetch(`/api/products?price=${budget}`);
    const data = await response.json();

    setParts(data.product);
  };
  return (
    <div>
      <h1>PC Parts Recommender</h1>
      <form onSubmit={handleSubmit}>
        <label>
          Enter your budget:
          <input type="number" value={budget} onChange={handleInputChange} />
        </label>
        <button className='btn btn-warning rounded ms-1' type="submit">Recommend Parts</button>
      </form>
      <ul>
        {items.map(product => (
          <li key={product.id}>{product.name} - ${product.price}</li>
        ))}
      </ul>
    </div>
  );
}

export default RecScreen;

React code In this code user enter budget and recommend pc parts but its show nothing and give this Uncaught TypeError: Cannot read properties of undefined (reading 'map')

2
  • What does the JSON response look like? If the response does not contain a product key, you're setting items to undefined. Commented Mar 19, 2023 at 17:47
  • What type do you see when you console.log(typeof data.product)? Commented Mar 19, 2023 at 17:59

2 Answers 2

0

Here the prolem is that the property product does not exist in the object data, however you are updating your state items with data.product which is undefined so when you try to map through items using items.map you are trying to map through an undefined value

To handle this use this code instead :

const handleSubmit = async (event) => {
  event.preventDefault();

  const response = await fetch(`/api/products?price=${budget}`);
  const data = await response.json();
  console.log(data) // see what your data object looks like
  if(data?.product){ // make this condition to only update the state when data exist and data.product exists
    setParts(data.product);
  }
};
Sign up to request clarification or add additional context in comments.

Comments

0

If data.product has a falsy value then in that case it will throw this error,you can modify this function like this

const handleSubmit = async (event) => {
    event.preventDefault();
    const response = await fetch(`/api/products?price=${budget}`);
    const data = await response.json();
    setParts(data.product || []);
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.