I have this markup and code on my page:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
import { useState, useEffect } from 'react';
import './Sidebar.css'
import TagsList from './TagsList';
const Sidebar = () => {
const [tags, setTags] = useState([]);
useEffect(()=>{
fetch('http://localhost:8000/tags')
.then(res=>{
res.json();
})
.then(data =>{
console.log(data);
})
}, [])
return (
<div className="side-content">
<div className="side-cont">
<div>Search (<a href="#">advanced</a>)</div>
<input type="text" />
<div>Hidden posts 0</div>
<div>
<TagsList tags={tags} title="Tags" />
</div>
</div>
</div>
);
}
export default Sidebar;
For some reason, when I try to fetch my data, the browser returns "undefined". Does anyone have a fix to this? Thank you so much
You have to return the res.json
.
fetch('http://localhost:8000/tags')
.then(response => response.json())
.then(data => setTags(data));
The issue is your format of the short-form function; the curly braces create scope and by default JS returns undefined in a function scope. Read more here.