1

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
Logesh P
  • 209
  • 4
  • 18
  • 1
    you're setting values initial value as an `{}` instead set it to `[]` – uday Jan 06 '20 at 06:51
  • for your initial `values` is a object . `Array.map` is a valid prototype .so change the initial `values` to array `const [values, setValues] = useState([])` – prasanth Jan 06 '20 at 06:53

3 Answers3

3

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

Learner
  • 8,379
  • 7
  • 44
  • 82
1

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>
  })
 }
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
0

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

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

to

const [values, setValues] = useState([]);
Hardik Chaudhary
  • 1,200
  • 1
  • 8
  • 24