Trying to fetch api data on frontend using useEffect hook,
i am able console log the data but unable to map it somehow
new to react
function SlugBook() {
// let {slug} = useParams(),
const [state, setState] = useState([])
useEffect(() => {
fetch("http://127.0.0.1:8000/app/reviews/",{CSRF_TOKEN....}
)
.then(response => response.json())
.then(data => console.log(data)) -->works fine
.then(data => setState(data)); --> not sure
})
return (
<p>
{state.map( d => (<li>{d}</li>))} ---> error code ()
</p>
)
}
export default SlugBook
Two problems:
then
like so: useEffect(() => {
fetch("http://127.0.0.1:8000/app/reviews/",{
credentials: 'include',
method: 'GET',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': CSRF_TOKEN
}})
.then(response => response.json())
.then(data => setState(data))
})
useRef
or else you will get infinite re-renders. So change it to: useEffect(() => {
fetch("http://127.0.0.1:8000/app/reviews/",{
credentials: 'include',
method: 'GET',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': CSRF_TOKEN
}})
.then(response => response.json())
.then(data => console.log(data)) -->works fine
.then(data => setState(data)); --> not sure
}, [])
Setting the dependancy array to an empty array []
will ensure that your useEffect
only runs your fetch
once on first render.