I am trying to use useState
hook and set the state after API call, but no matter how much time it never updates.
I want to use that state in other component using useContext
. Now I only want my route to it when my state gets updated. How to achieve it?
My code:
const [openedFeedback, setOpenedFeedback] = useState<ProductRequest>({id: 0, title: '', category: '', upvotes: 0, status: '', description: '', comments: []})
const getFeedbackById = async (id: number) => {
const url = `${host}api/product-requests/${id}`
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
headers: {
'Content-Type': 'application/json',
}
});
const json = await response.json()
setOpenedFeedback(json);
}
The code for routing, triggers on click:
const openFeedback = async (id: number) => {
await getFeedbackById(id)
router.push('/components/feedback-detail')
}
Other component:
import Link from 'next/link'
import React, { useContext, useEffect } from 'react'
import './FeedbackDetails.scss'
import FeedbackContent from '../FeedbackContent'
import FilterContext from '@/app/context/filters/FilterContext'
export default function FeedbackDetails() {
const { openedFeedback } = useContext(FilterContext)
useEffect(() => {
setFeedback(openedFeedback)
console.log(feedback);
}, [openedFeedback])
return (
<div className='outer-container'>
<div className="inner-container">
<div className="btns-container">
<Link href='/' className='back-btn'>
<svg width="7" height="10" xmlns="http://www.w3.org/2000/svg"><path d="M6 9L2 5l4-4" stroke="#4661E6" strokeWidth="2" fill="none" fillRule="evenodd" /></svg>
<span>Go Back</span>
</Link>
<Link href='/' className='edit-btn'>Edit Feedback</Link>
</div>
<div className="content-container">
<FeedbackContent id={openedFeedback.id} title={openedFeedback.title} category={openedFeedback.category} upvotes={openedFeedback.upvotes} comments={openedFeedback.comments} description={openedFeedback.description} status={openedFeedback.status} />
</div>
</div>
</div>
)
}