Answer the question
In order to leave comments, you need to log in
Why is there no data fetched (React)?
Help me figure it out, it seems like I'm doing everything as it is written in the off-documentation example, but I get an error: Cannot read properties of null (reading 'map'). You need to make a request to the server, get the data and display it in the DOM.
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(
(data) => {
setIsLoaded(true);
setData(data);
},
(error) => {
setIsLoaded(true);
setError(error)
}
)
},[]);
if(error){
return <div>Data loading error: {error.message}</div>
} else if(!isLoaded){
return <div>Loading...</div>
} else{
return (
<div className="dashboard">
{data.map(item => (
<h1>{item.title}</h1>
))}
</div>
);
}
}
Answer the question
In order to leave comments, you need to log in
The question is meaningless, the data is there.
fetch('https://jsonplaceholder.typicode.com/todos/1')
1
.const [data, setData] = useState(null);
{data.map(item => (
null
method exist map
? - google it, figure it out. Well, replace null
with []
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question