Home > Back-end >  TypeError: users.map is not a function React js
TypeError: users.map is not a function React js

Time:12-08

am stuck with a problem , am try to solve it lots of time but am not able to solve it , please try to fix my error. If you have any query please free feel to ask.

Userdata.js

This is the userdata.js file where I want to load my all data which are in backend database

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

const UserData = () => {
  const [users, setUser] = useState({
    title : "",
    description : ""
  });

  const {id} = useParams();

  useEffect(() => {
    AllUsers();
  }, []);

  const AllUsers = async () => {
    const res = await Axios.get(`http://localhost:3000/${id}`);
    console.log(res.data);
    setUser(res.data)
  };

  return (
    <div>
      <div className="container">
        <table className="table table-hover table-bordered mt-5">
          <thead>
            <tr>
              {/* <th scope="col">No</th> */}
              <th scope="col">Title</th>
              <th scope="col">Details</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user, index) => (
              <tr key={index}>
                <th scope="row">{user.id}</th>
                <td>{user.title}</td>
                <td>{user.description}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default UserData;

CodePudding user response:

users looks to me to be an object, not an array. The map() function exists only on Array's prototype, so you can't call it on your users object. Did you mean to initialize users like this?

 const [users, setUser] = useState([{
    title : "",
    description : ""
  }]);

CodePudding user response:

The map method is defined on on array and not on objects. Lets look at your code

  const [users, setUser] = useState({
    title : "",
    description : ""
  });

In UserData component you defined an object state with properties title and description. So users will be an object with those properties. Thus when you try to apply map on the users object it fails since map is not a function defined on objects.

Instead if you want to have an array of users with those two properties you can declare the state as follows

  const [users, setUser] = useState([{
    title : "",
    description : ""
  }]);
  • Related