How do I map through an unnamed array in React? - reactjs

I have an array that looks like this.
[{"id":19,"name":"asd","salary":123},{"id":20,"name":"wer","salary":1}]
But when I try to map through it in React I get an Error
Uncaught TypeError: data.map is not a function
import React, { Component, useState, useEffect } from 'react';
function EmployeeList() {
const [data, setData] = useState({ items : [] });
const getEmployees = () => {
fetch("http://127.0.0.1:8000/api/employee-list")
.then((response) => response.json())
.then((data) => {
setData(data);
console.log(data);
})
};
useEffect(() => {
getEmployees();
}, [])
return (
<div>
<ul>
{data.map((employee) =>
<li>{employee.name}</li>
)}
</ul>
</div>
)
export default EmployeeList;

That's because you are not setting data to an array, but an object at first. Use this instead:
const [data, setData] = useState([]);
This assumes that your data comes back from the API as you specified, i.e., as an array. If instead it comes back in the format suggested by your original initial value then you'd need to use:
{data && data.items && data.items.map((employee) =>

Related

Why I have error when use Api from DummyJSON

Run code and I get "Consider adding an error boundary to your tree to customize error handling behavior.: How can I fix it
import React, { useState, useEffect } from "react";
const BASE_URL = "https://dummyjson.com/products";
export default function App() {
const [product, setProduct] = useState([]);
useEffect(() => {
fetch(`${BASE_URL}`)
.then((res) => res.json())
.then((res) => {
setProduct(res);
})
// .then(console.log)
}, []);
return (
<ul>
{product.map((item) => (
<li key={item.id}>
{item.products.brand}
</li>
))}
</ul>
);
}
I tried change another API and it dose not have error
The problem is what type of data in file json. In this case data' type is object so I can not use map to render product.
first I change useState hook from empty array to object
const [product, setProduct] = useState({ products: [] });
then fetch data from api
const fetchData = () => {
fetch(`${BASE_URL}?limit=5`)
.then((res) => res.json())
.then((data) => {
setProduct(data);
});
};
useEffect(() => {
fetchData();
});
after fecth data and set to state I render it

React fetch api data not being displayed

I have a simple fetch request that runs only on the first render. When I update the state with the data and try to map through it nothing is shown. For reference the data I am given back is just one entry. Using .map it should for each entry ( which is 1) display a bullet but nothing is shown.
{quote: "I'm the new Moses"}
import logo from './logo.svg';
import {useState,useEffect} from 'react';
import './App.css';
function App() {
const [users, setUsers] = useState([])
const fetchData = () => {
fetch("https://api.kanye.rest/")
.then(response => {
return response.json()
})
.then(data => {
console.log(data)
setUsers(data)
})
}
useEffect(() => {
fetchData()
}, [])
return (
<div className="App">
<body className='App'>
<div>
{users.length > 0 && (
<ul>
{users.map(user => (
<li>{user.quote}</li>
))}
</ul>
)}
</div>
</body>
</div>
);
}
export default App;
The response value {quote: "I'm the new Moses"} is an object, not an array. It can't be mapped.
Place the response value in an array when saving.
const fetchData = () => {
fetch("https://api.kanye.rest/")
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
setUsers([data]);
});
};
The result you got isn't an array, it's an object. It can't be mapped. However, you can achieve your expected behaviour in many ways. One of them is just put data into an array while setting user.
setUsers([data])

Cannot read property 'map' of undefined on useState value

I'm new to react, I'm getting this error constantly and after google some I can't find the reason why the useState value can't be read as array :( ... this the error I'm getting: 'TypeError: team.map is not a function'
import React, { useEffect, useState } from "react";
const SportTeams = () => {
const [team, setTeam] = useState([]);
useEffect(() => {
const getSports = async () => {
const response = await fetch("https://www.thesportsdb.com/api/v1/json/1/all_sports.php");
const data = await response.json();
setTeam(data);
console.log(data);
}
getSports();
}, []);
return (
<div className="myClass">
<ul>
{team.map((sport, index) => {
return <li key={`${sport.strSport}-${index}`}>{sport.strSport}</li>
})}
</ul>
</div>
);
};
export default SportTeams;
Just update setTeam like following, your error will be resolved.
setTeam(data.sports);
It is because you are setting the team state with the data without checking if its undefined. If the data is undefined your state team become undefined as well. So make sure to check the data.
import React, { useEffect, useState } from "react";
const SportTeams = () => {
const [team, setTeam] = useState([]);
useEffect(() => {
const getSports = async () => {
const response = await fetch("https://www.thesportsdb.com/api/v1/json/1/all_sports.php");
if (response) {
const data = await response.json();
if (data) {
setTeam(data);
}
}
console.log(data);
}
getSports();
}, []);
return (
<div className="myClass">
<ul>
{team.map((sport, index) => {
return <li key={`${sport.strSport}-${index}`}>{sport.strSport}</li>
})}
</ul>
</div>
);
};
export default SportTeams;
There might also be the chance that your response is not what you expected and the actual data might be inside your response. In that case you need check what your response first then proceed to set the data.
As I said in my comment. the value you are setting to teams isn't an array.
const data = await response.json();
setTeam(data.sports);

How to fetch data from restAPI and from localStorage at a time?

What I am doing is to load data from my local storage which I have fetched from https://jsonplaceholder.typicode.com/users. I am trying to create a react application in which I have added multiple users as a friend just like facebook. my friend list is in the file called UserInfo.js which code I have given bellow. then I tried to show friends corresponding to their id by comparing with the id which I tried to find from api call so that this can show me the matching users.
You can find my project here: https://codesandbox.io/s/elastic-dream-mp3is?file=/src/App.js
import React, { useState } from "react";
import "./UserInfo.css";
import { useEffect } from "react";
import fakedata from "../../fakedata";
import { getDatabaseCart } from "../../utilities/databaseManager";
const UserInfo = () => {
// // using fakedata
// const [users, setUsers] = useState(fakedata);
// // declaring state while calling api
const [users, setUsers] = useState([]);
// declaring state while loading data from local storage
const [friends, setFriends] = useState(users);
// to load data from Api call
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);
// to load data from local storage
useEffect(() => {
const savedFriends = getDatabaseCart();
const friendsId = Object.keys(savedFriends);
const countFriends = friendsId.map((key) => {
const friend = friends.find((fd) => fd.id == key);
// console.log(friend);
return friend;
});
setFriends(countFriends);
}, [friends]);
// console.log(friends);
// console.log(users);
return (
<div className="userInfo-container">
<div className="userInfo">
{friends.map((friend) => (
<div>
<h4>Name: {friend.name}</h4>
</div>
))}
</div>
</div>
);
};
export default UserInfo;
I have created fakedata collecting data from jsonplaceholder and tested according to above method and it worked perfectly. but when I tried to load data API call, I got the following error:
the first error indicates that it can not read property of name which I tried to return from local Storage after matching the id with api call.
2.second error denotes which I can't understand in my case. I have tried abortCall to handle this error. the error gone but my problem still exits. what can I do now????
With hooks:
import React, { useState } from "react";
//import "./UserInfo.css";
import { useEffect } from "react";
import fakedata from "../../fakedata";
import { getDatabaseCart } from "../../utilities/databaseManager";
const UserInfo = () => {
// // using fakedata
// const [users, setUsers] = useState(fakedata);
// // declaring state while calling api
const [users, setUsers] = useState([]);
// declaring state while loading data from local storage
const [friends, setFriends] = useState([]);
// to load data from Api call
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);
// to load data from local storage
useEffect(() => {
const savedFriends = getDatabaseCart();
const friendsId = Object.keys(savedFriends);
setFriends(friendsId);
}, []);
// console.log(friends);
// console.log(users);
return (
<div className="userInfo-container">
<div className="userInfo">
{users.length > 0 && friends.map((friendId) => {
const friend = users.find(user => user.id === parseInt(friendId));
return (
<div>
<h4>Name: {friend && friend.name}</h4>
</div>
)})}
</div>
</div>
);
};
export default UserInfo;
In the render, Friends return [{0:undefined}]. You are not setting friends correctly.
I make a Class version of your UserInfo component. It works like this.
import React from "react";
import { getDatabaseCart } from "../../utilities/databaseManager";
class UserInfo extends React.Component {
state = {
users: [],
friends: []
}
componentDidMount = () => {
this.getDataFromServer();
this.getDateFromLocalStorage();
}
getDataFromServer = () => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => this.setState({users:data}));
}
getDateFromLocalStorage = () => {
const savedFriends = getDatabaseCart();
const friendsId = Object.keys(savedFriends);
//console.log(friendsId)
this.setState({friends:friendsId})
}
render() {
const {users, friends} = this.state;
// console.log('users',users, friends);
// console.log('friends', friends);
return (
<div className="userInfo-container">
<div className="userInfo">
{users.length > 0 && friends.map((friendId) => {
const friend = users.find(user => user.id === parseInt(friendId));
return (
<div>
<h4>Name: {friend && friend.name}</h4>
</div>
)})}
</div>
</div>
);
}
}
export default UserInfo;
Note you have a promise for the 'fetch' so at first render and until users are fetched user = [] empty array. To avoid errors it's good to check the length of users before try to map friends.
You can remove the friend check here because if friends array is empty, there is nothing to map.
return (
<div>
<h4>Name: {friend.name}</h4>
</div>
)
Now, it should be a list with ul and li.

React .map an object

I've got an eslint error Property 'date' does not exist on type 'never', and it's on data.date. Any idea how can I fix it?
import React from 'react'
import app from './../Flamelink'
function App() {
const [data, setData] = React.useState([])
React.useEffect(() => {
const fetchData = async () => {
const data = await app.content.get({
schemaKey: 'persons'
})
setData(data)
}
fetchData()
}, [])
return (
<ul>
{data.map(data => (
<li>{data.date}</li>
))}
</ul>
)
}
export default App
First of all, I would use a different variable name instead of just calling everything data. This way you avoid variable shadowing errors.
If you want your state variable to be data then call the answer you get from your fetch something else, result maybe. Then, when mapping your data state, call the current value something else too, maybe item or dataItem.
Second, since you appear to be using TypeScript, you need to tell TS the structure of your data state array.
Try this:
function App() {
const [data, setData] = React.useState<Array<{date: string}>>([]);
React.useEffect(() => {
const fetchData = async () => {
const result = await app.content.get({
schemaKey: "persons"
});
setData(result);
};
fetchData();
}, []);
return (
<ul>
{data.map(item=> (
<li>
{item.date}
</li>
))}
</ul>
);
}

Resources