Logesh P
Logesh P

Reputation: 227

values.map is not a function reactjs

i am fetchin details from database wanted to display that into the table, but for initial purpose i wanted to just display on browser without table and stuff.. am getting values.map is not a function but i could the see values printed in console

here iam using function component

export default function SimpleTable() {
const [values, setValues] = useState({});

here is the fetch function

async function handleTable(){
const res = await fetch("http://localhost:4000/productslist")
const data = await res.json()
setValues(data.data)
console.log(data.data)
}

calling the fetch function on useEffect

useEffect(()=>{
handleTable()
},[])

Rendering the values into browser

return (
<div>

{console.log(values)}
{values.map(v => {
return  <h4 key={v.idaddproducts}>{v.productName}{v.productId}{v.productBrand}</h4>})}
</div>
);
}

here is the error

Uncaught TypeError: values.map is not a function

Upvotes: 1

Views: 3476

Answers (3)

Beginner
Beginner

Reputation: 9105

The initial state of your values is an empty object

From

const [values, setValues] = useState({});

Update to

const [values, setValues] = useState([]);

Since Object doesn't have a method called .map

Also in your code since its a async call you can check based on a state whether data has load or not a simple thing you can add is a ternary check

{values.length && values.map(v => {
return  <h4 key={v.idaddproducts}>{v.productName}{v.productId}{v.productBrand}</h4>})}
</div>
);

so once the array has a length greater than zero only it will execute the map function

Working Codesandbox With Sample Example

Upvotes: 3

akhtarvahid
akhtarvahid

Reputation: 9769

Define your state as an array

const [values, setValues] = useState([]);

Code

{values && values.map(v => {
  return  <h4 key={v.idaddproducts}>
           {v.productName}{v.productId}{v.productBrand} 
          </h4>
  })
 }

Upvotes: 1

Hardik Chaudhary
Hardik Chaudhary

Reputation: 1228

You set a value {} instead of []. Update

const [values, setValues] = useState({});

to

const [values, setValues] = useState([]);

Upvotes: 0

Related Questions