I have the following urls that route to the same component. I want to use the same component for two scenarios, either a new blank version or an existing one which is then pre-populated via API fetch using the url parameter.
Once I change my url from e.g.
http://localhost:3000/dashboard/planner/1
to
http://localhost:3000/dashboard/planner/
the component remains its state and doesn't reset. The console.log in useEffect
also doesn't re-trigger.
My approach was to define a boolean logic is_existing_offer
in the useEffect
hook.
So I guess I need to somehow re-render the component once changing the url as I can't call useEffect
again or use another method to update its state when jumping to http://localhost:3000/dashboard/planner/
?
<Routes>
<Route key="planner_id" path="planner/:id" element={<PlannerWrapper is_existing_offer={true}/>}/>
<Route key="planner_default" path="planner/" element={<PlannerWrapper is_existing_offer={false}/>}/>
</Routes>
// PlannerWrapper
const PlannerWrapper = (props) => {
// Get the offer's uuid from route to make API call and fetch the offer
const params = useParams()
..
// Fetch the associated offer via API and pre-populate components, only runs once at mount
// Only runs if it is not the blank planner instance
useEffect(() => {
if (props.is_existing_offer) {
fetch(`http://127.0.0.1:8000/api/offer/${params.id}`, {
method: 'GET',
headers: {'Content-Type': 'application/json'},
})
.then(res => res.json())
.then(result => {
console.log('Success:', result);
setValues(result)
})
}
else {
setValues(initial_state)
}
}, []);