Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic routing and lifecycle in react

I'm working with dynamic routing in react. I'm fetching some data from a third-party API. I have my dynamic route to be something like this

<Route path="/:id" component = {item} />

In the item component, I get the value in params.id and use that id to fetch my data in

componentDidUpdate(){ fetchData(this.props.match.params.id);}

The issue I'm having now is that whenever I try to visit another route of the same format /:id from the Item component, the params changes to the new id passed but still retains the old content for the old id. I believe componentDidmount wasn't called since i'm in that same item component. the component wasn't remounted but just updated. What can I do?

like image 690
Hilory Avatar asked May 06 '26 07:05

Hilory


1 Answers

You have to make the api call in componentDidMount as well as in componentDidUpdate with class component. Once you fetch the data, you have to set it in state of the component to visually see it.

componentDidmount() {
  fetchData(this.props.match.params.id);
}

componentDidUpdate(prevProps, prevState){
  if(prevProps.match.params.id !== this.props.match.params.id) {
    fetchData(this.props.match.params.id);
  }
}

If you rather use react hooks + functional component, this will be simplified for you. You can use useState to maintain data in the state.

import React, { useEffect } from "react";
const YourComponent = props => {
    const { id } = props.match.params;
    // This will run every time id changes.
    useEffect(() => {
        fetchData(id);
    }, [id]); 

    return (
        <>
            Your api call
        </>
    );
};
like image 141
Avanthika Avatar answered May 07 '26 21:05

Avanthika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!