Call componentDidMount() manually even if component is already mounted

94 Views Asked by At

I have a class Dashboard component which fetch data from multiple API's in componentDidMount() with props received from route and renders a charts.

    componentDidMount() {
        this.urls = ChartProps[this.chart].api;
        this.title = ChartProps[this.chart].titles;
        
        Promise.all(
                    urls.map(url =>
                    fetch(url)
                    .then((res) => res.json())
                    .catch(error => console.log('There was a problem!', error))
                ))
                .then((json) => {
                    this.formatJsonForChart(json);
                });
        
    }

Now there are different props from different routes get received on same component.

    <BrowserRouter>
        <Navlist/>
        <Routes>
            <Route path="/" element={<Dashboard element={<Dashboard chart='chart1'/>} />} />
            <Route path="/chart2" element={<Dashboard chart='chart2'/>} />
            <Route path="/chart3" element={<Dashboard chart='chart3'/>} />
            <Route path="/chart4" element={<Dashboard element={<Dashboard chart='chart4'/>} />} />
            <Route path="*" element={<ErrorPage />} err='404' />
        </Routes>
    </BrowserRouter>

All the API's that fetches a data are based on received props. The problem here is function that renders a chart get called in componentDidMount() so it works fine on first route click. But when clicked on other route it doesn't call componentDidMount() since component is already mounted so charts doesn't get updated get clicked on other route.

What alternate approach can be taken?

1

There are 1 best solutions below

0
Drew Reese On

You could abstract the logic in your componentDidMount lifecycle method into a function that is called in both componentDidMount and componentDidUpdate lifecycle methods.

OR

Provide a unique React key to each Dashboard component so when the route changes React will unmount/remount a new instance.

<BrowserRouter>
  <Navlist/>
  <Routes>
    <Route
      path="/"
      element={<Dashboard key="/chart1" chart='chart1'/>}
    />
    <Route
      path="/chart2"
      element={<Dashboard key="/chart2" chart='chart2'/>}
    />
    <Route
      path="/chart3"
      element={<Dashboard key="/chart3" chart='chart3'/>}
    />
    <Route
      path="/chart4"
      element={<Dashboard key="/chart4" chart='chart4'/>}
    />
    <Route path="*" element={<ErrorPage />} err='404' />
  </Routes>
</BrowserRouter>