React axios response data does not appear (TypeScript)

Viewed 50

I want to show in table the datas from the api request, but nothing appears. The data is written to the console. (console.log("Response data: " + users.data))

The response like: [{"UserName":"","PartnerID":"0"},{"UserName":"Asd","PartnerID":"3"},{"UserName":"Asd","PartnerID":"3"},{"UserName":"Asd","PartnerID":"3"},{"UserName":"Asd","PartnerID":"3"},{"UserName":"demo","PartnerID":"3"},{"UserName":"demo","PartnerID":"3"},{"UserName":"Asd","PartnerID":"3"}]

const ListUsers: React.FC = () => {
    type ServerData = {
        userName: string;
        PartnerID: number;
    }

    const [data, setData] = useState<ServerData[]>([]);
    const getData = async (): Promise<void> => {
        await axios.post<ServerData[]>(LIST_ALL_USER)
        .then(users => {
            console.log("Response data: " + users.data)
            setData(users.data);
        })
    }

    useEffect(() => {
        getData()
        console.log("Input data " + data)       //Is empty?
    }, []);

In return:

<tbody>
    {data.map((user, index) => (
        <tr key={index}>
            <td>
                <div className='d-flex align-items-center'>
                    <div className='d-flex justify-content-start flex-column'>
                        <span className='text-dark fw-bolder fs-6'>
                            {user.userName}
                        </span>
                        <span className='text-muted fw-bold text-muted d-block fs-7'>
                            HTML, JS, ReactJS
                        </span>
                    </div>
                </div>
            </td>
            <td>
...

What is the problem? Pls help

This code snippet is available in here: https://pastebin.com/bK3X2R1B

1 Answers

Try changing user.userName to user.UserName as defined in the data you mentioned above

<tbody>
    {data.map((user, index) => (
        <tr key={index}>
            <td>
                <div className='d-flex align-items-center'>
                    <div className='d-flex justify-content-start flex-column'>
                        <span className='text-dark fw-bolder fs-6'>
                            {user.UserName} // <-- Here
                        </span>
                        <span className='text-muted fw-bold text-muted d-block fs-7'>
                            HTML, JS, ReactJS
                        </span>
                    </div>
                </div>
            </td>
            <td>
Related