mig_08
mig_08

Reputation: 181

React router not reloading data

When I click on the navigation bar to a path with a different id it does not fetch the data related to that id.

Code:

import React, { Component } from 'react';
import { Route, Switch } from "react-router-dom";
import { Layout } from './components/Layout';
import JobsIndex from './components/jobs/jobs_index';
import JobItems from './components/jobs/job_items';
import SupplierShow from './components/supplier/supplier_index';
import UsersIndex from './components/users/users_index';
import './custom.css'

export default class App extends Component {
  static displayName = App.name;

  render () {
    return (
      <Layout>
        <Switch>   
          <Route path="/jobitems/:id" component={JobItems} />
          <Route path="/jobs" component={JobsIndex} />  
          <Route path="/supplier" component={SupplierShow} />  
          <Route exact path="/users/:id" component={UsersIndex} />
        </Switch>
      </Layout>  
    );
  }
}

When I click on the Users tab it just changes the URL to https://localhost:44312/users/0 without refreshing data. Users/0 returns all users and Users/1 returns a specific user. Not too sure what I am missing. enter image description here

UserIndex Code:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../../actions/users';

class UsersIndex extends Component {
    componentDidMount() {
      const id = this.props.match.params.id;
      this.props.fetchPost(id);
      this.state.id = id;
    }
    
    constructor(props) {
      super(props);
      this.onSubmit = this.onSubmit.bind(this);
  }

  state = {
      visible: false,
      active: true,
      errors: {},
      id: 0
    }

Upvotes: 1

Views: 65

Answers (1)

Omar Sy
Omar Sy

Reputation: 496

When you change your id react doesn't delete and create a new component. It is going to update your component then call componentdidupdate

import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import { fetchPost } from '../../actions/users';
    
        class UsersIndex extends Component {
    componentDidMount() {
          const id = this.props.match.params.id;
          this.props.fetchPost(id);
          this.state.id = id;
        }
            componentDidUpdate(prevProps) {
             if(this.props.match.params.id  !== prevProps.match.params.id){
              const id = this.props.match.params.id;
              this.props.fetchPost(id);
              this.state.id = id;
        }
            }
            
            constructor(props) {
              super(props);
              this.onSubmit = this.onSubmit.bind(this);
          }
        
          state = {
              visible: false,
              active: true,
              errors: {},
              id: 0
            }

Upvotes: 1

Related Questions