0
votes

Im trying to use my api created in node witn the axios library and hook useEffect to display current item users and I'm getting error Uncaught (in promise) TypeError: Cannot read property 'recordset' of undefined, whY? API

router.get('/api/users, async(req,res)=>{
    try {
        let results=await m.all();
        res.json(results)
    } catch (error) {
        console.log(error);
        res.sendStatus(500);
    }
});

Data

{
    "recordset": [
        [
            {
                "id":1,
                "Name":"Alissa",
                "Age": 45,
                "Adress": "Brooklyn 405",
                "Phone": "212-324-4153"
            },
            {
                "id":2,
                "Name":"Ellis",
                "Age": 23,
                "Adress": "Boston 955",
                "Phone": "212-324-4152"
            }

    ],
    "output": {},
    "rowsAffected": [
        2
    ]
}

Function to call my API created in node js with react hooks useEffect and axios library

import React, { useState, useEffect } from 'react';
import  axios  from 'axios';
import { Link } from 'react-router-dom';


 function AllUsers(){
    const url='/api/users';
    const[user, setuser]= useState({recordset: [] });

    useEffect(()=>{
        const getUsers=async()=>{

                const response =await axios.get(url);
                setuser(response.user);

        }
        getUsers();
    },[]);
    return(
        <ul>
        {user.recordset.map(item=>(
            <li key={item.id}>
            <a href={item.url}>{item.Name}</a>
            </li>
        ))}
        </ul>
    )
 }

 export default AllUsers;
2
As I know, real data will be in data property of axios response. Try to use response.data.user` instead.thelonglqd
@dqlgnoleht Now throw the TypeError error: Cannot read property 'recordset' of undefinedEmm
Could you edit your post and add the response ?thelonglqd
@dqlgnoleht You were right was to put the data but without the .userEmm
"recordset": [ [ <---- delete this one, you have two, one of them should be deletedRafael Mora

2 Answers

0
votes

Please try changing this line:

setuser(response.user);

to,

setuser(response);

Looks like your response data doesn't have a object with key user.

0
votes

It was to use the data property of axios as mentioned by the partner

import React, { useState, useEffect } from 'react';
import  axios  from 'axios';
import { Link } from 'react-router-dom';


 function AllUsers(){
    const url='/api/users';
    const[user, setuser]= useState({recordset: [] });

    useEffect(()=>{
        const getUsers=async()=>{

                const response =await axios.get(url);
                **setuser(response.data);**

        }
        getUsers();
    },[]);
    return(
        <ul>
        {user.recordset.map(item=>(
            <li key={item.id}>
            <a href={item.url}>{item.Name}</a>
            </li>
        ))}
        </ul>
    )
 }

 export default AllUsers;