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;
CodePudding user response:
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]);
});
};
CodePudding user response:
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])