Aleem Raza
Aleem Raza

Reputation: 1

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

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')

Upvotes: 0

Views: 201

Answers (2)

pinku kumar
pinku kumar

Reputation: 129

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 || []);
  };

Upvotes: 0

Ahmed Sbai
Ahmed Sbai

Reputation: 16219

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);
  }
};

Upvotes: 0

Related Questions