I'm trying to map
user data to the render component (WidgetSm.jsx) using useState
and useEffect
hooks. But I'm getting this error in console.dev
:
Uncaught TypeError: users.map is not a function
How to resolve this error?
My codes:
Front/React:
WidgetSm.jsx:
import "./widgetSm.css";
import { Visibility } from "@material-ui/icons";
import { useEffect, useState } from "react";
import { userRequest } from "../../requestMethods";
export default function WidgetSm() {
const [users, setUsers] = useState([]);
useEffect(() => {
const getUsers = async () => {
try {
const res = await userRequest.get("users/?new=true");
setUsers(res.data);
} catch {}
};
getUsers();
}, []);
return (
<div className="widgetSm">
<span className="widgetSmTitle">New Join Members</span>
<ul className="widgetSmList">
{users.map((user) => ( //error located at this line
<li className="widgetSmListItem" key={user._id}>
<img
src={
user.img ||
"https://cdn.elearningindustry.com/wp-content/themes/eli-2015/assets/images/mystery-man.png"
}
alt=""
className="widgetSmImg"
/>
<div className="widgetSmUser">
<span className="widgetSmUsername">{user.username}</span>
</div>
<button className="widgetSmButton">
<Visibility className="widgetSmIcon" />
Display
</button>
</li>
))}
</ul>
</div>
);
}
RequestMethods.js:
import axios from "axios";
const BASE_URL = 'http://localhost:5000/api/';
const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user).currentUser.accessToken;
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
headers: { token: `Bearer ${TOKEN}` }
});
Back/models:
Users.js:
const mongoose = require("mongoose")
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
isAdmin: {
type: Boolean,
default: false
},
img: {
type: String
}
},
{ timestamps: true }
)
module.exports = mongoose.model("User", UserSchema);
Edit:
I'm not sure if this error is related to the map but I found it in console.dev
too:
<tr>
cannot appear as a child of<table>
. Add a<tbody>
,<thead>
or<tfoot>
to your code to match the DOM tree generated by the browser.
CodePudding user response:
The TypeError
indicates that whatever the user variable is at runtime time, it is not an array js docs.
Since you have no provided any code for your requestMethods I cannot comment on any error there but I assume you are aiming for some output that follows...
var users = [{userObject}, ...{finalUser}]
where each userObject is in the form of the schema you provided. To resolve this mismatch I suggest you make several breakpoints/test cases to make sure you have an array with your user data before trying to render it.
If it is the case that you are just retrieving a single user with your request then the issue may be that it is not wrapped in an array and therefore would also throw a TypeError
when attemping to use map on it. In this case modify your request output to always come wrapped in an array.
CodePudding user response:
{Object.values(users).map((user) => ( the rest of the code ))}
try using object.values instead of users.map
sometimes when u fetch data from some api to array ,it turnes to object , that worked for me