I am fetching dynamic submenu from database under a menu. My problem is when I clicked a submenu it works fine and view is also changing. After that any submenu I clicked it doesn't changing it's view content which is also fetching from database, but URL is changing.
Like I have a menu called Services, and under this there are dynamic submenu fetched using API.
Service Menu
In App.js
class App extends React.Component {
render() {
return (
<div>
<Router>
<Header />
<div>
<Switch>
<Route path="/contact">
<Contact />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/service/:id">
<Service />
</Route>
<Route path="/">
<Homepage />
</Route>
</Switch>
</div>
<Footer />
</Router>
</div>
);
}
}
export default App;
if (document.getElementById('app')) {
ReactDOM.render(<App />, document.getElementById('app'));
}
In Service.js page
const Service = (props) =>{
const [service, setservice] = useState([]);
const id = props.match.params.id;
React.useEffect(() => {
fetch("http://127.0.0.1:8000/api/service/"+ id)
.then(results => results.json())
.then(res => {
const service = res.data.service;
setservice(service);
});
}, []);
return (
<div>
{
service.map((service, index) =>(
<div key={index}>
<h6 className="heading ">{service.service_name}</h6>
</div>
))
}
</div>
);
}
export default withRouter(Service);
"That's because you're running your function once, you need it to make it run every time there's a new click. Inside your useEffect , try to put id as a dependency and see what happens"...
const id = props.match.params.id
React.useEffect(() => {
fetch('http://127.0.0.1:8000/api/service/' + id)
.then((results) => results.json())
.then((res) => {
const service = res.data.service
setservice(service)
})
}, [id])