Search code examples
reactjsreact-componentreact-statereact-state-management

how can I update a state in react using axios.get method?


I have a layout where there is a navbar as a separate component and the remaining of the page, my problem is when I change the showing Classes in the navbar I want the page to change it's states to show the related info for each class, I am getting all the needed info from the navbar, so the problem is not there, I think the problem is in the Class.js file on how to update the state, please help anyone, here is the Class.js file:

class Class extends React.Component {
    
    static contextType = userContext
    
    state = {
        Curriculum: [],
        Classworks: [], 
        Homeworks: []
    }

    componentDidMount() {
        console.log(this.props.location.state)
        const provided = this.props.location.state.ClassNumber
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                'Accept': 'application/json'
            }
        }; 
        axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
            .then(
                res => {
                    this.setState(
                        {
                            Curriculum: res.data 
                        }
                    );
                }
            )                      
      }
      componentDidUpdate(){
        const provided = this.props.location.state.ClassNumber
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                'Accept': 'application/json'
            }
        }; 
        axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
            .then(
                res => {
                    this.setState(
                        {
                            Curriculum: res.data 
                        }
                    );
                }
            )  
      }
    render()
        {       
            console.log(this.state.Curriculum);       
            return(
            <div className="back">
            <Navbar/>
            
            <main className= "MainContent">
                <div className="Class">
                    <h2 className="class">
                        {this.props.location.state.Name}
                    </h2>
                </div>
                <Tabs  className="Tabs" defaultActiveKey="1" centered>
                    <TabPane tab="Curriculum"  key="1">
                        <List
                        itemLayout="horizontal"
                        dataSource={this.state.Curriculum}
                        renderItem={item => (
                            <List.Item>
                                <Table striped bordered hover size="sm" >
                                    <tr>
                                        <th>
                                            #
                                        </th>
                                        <th>
                                            Title
                                        </th>
                                    </tr>
                                    <tr>
                                        <td>
                                            
                                        </td>
                                        <td>
                                            {item.Title}
                                        </td>
                                    </tr>
                                </Table>
                            </List.Item>
                        )}
                        />
                    </TabPane>
                    <TabPane tab="ClassWorks"  key="2">
                    
                    </TabPane>
                    <TabPane tab="HomeWorks" key="3">
                        
                    </TabPane>
                    <TabPane tab="Videos" key="4">
                    
                    </TabPane>
                    <TabPane tab="Sessions" key="5">
                    
                    </TabPane>
                    <TabPane tab="quizzes" key="6">
                    
                    </TabPane>
                    <TabPane tab="Exams" key="7">
                    
                    </TabPane>
                </Tabs>
            </main>
            <br/>
            <footer className="Footer">Designed by Eng. Omar Redwan</footer>
        </div>
        )}
}

Solution

  • I think your problem is with updating the state right?. Then you have to pass prevProps and prevState as params to componentDidUpdate. To track the changes in props you have to fetch prevProps and componentDidUpdate calls only when there is a change in props. That means when the location props changes then it will update the state which you needed to do.

    class Class extends React.Component {
        
        static contextType = userContext
        
        state = {
            Curriculum: [],
            Classworks: [], 
            Homeworks: []
        }
    
        componentDidMount() {
            console.log(this.props.location.state)
            const provided = this.props.location.state.ClassNumber
            const config = {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `JWT ${localStorage.getItem('access')}`,
                    'Accept': 'application/json'
                }
            }; 
            axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
                .then(
                    res => {
                        this.setState(
                            {
                                Curriculum: res.data 
                            }
                        );
                    }
                )                      
          }
          componentDidUpdate(prevProps,prevState){
    if(prevProps.location.state.classNumber!==this.props.location.state.classNumber){
            const provided = this.props.location.state.ClassNumber
            const config = {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `JWT ${localStorage.getItem('access')}`,
                    'Accept': 'application/json'
                }
            }; 
            axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Curriculum/${provided}`, config)
                .then(
                    res => {
                        this.setState(
                            {
                                Curriculum: res.data 
                            }
                        );
                    }
                )
    }  
          }
        render()
            {       
                console.log(this.state.Curriculum);       
                return(
                <div className="back">
                <Navbar/>
                
                <main className= "MainContent">
                    <div className="Class">
                        <h2 className="class">
                            {this.props.location.state.Name}
                        </h2>
                    </div>
                    <Tabs  className="Tabs" defaultActiveKey="1" centered>
                        <TabPane tab="Curriculum"  key="1">
                            <List
                            itemLayout="horizontal"
                            dataSource={this.state.Curriculum}
                            renderItem={item => (
                                <List.Item>
                                    <Table striped bordered hover size="sm" >
                                        <tr>
                                            <th>
                                                #
                                            </th>
                                            <th>
                                                Title
                                            </th>
                                        </tr>
                                        <tr>
                                            <td>
                                                
                                            </td>
                                            <td>
                                                {item.Title}
                                            </td>
                                        </tr>
                                    </Table>
                                </List.Item>
                            )}
                            />
                        </TabPane>
                        <TabPane tab="ClassWorks"  key="2">
                        
                        </TabPane>
                        <TabPane tab="HomeWorks" key="3">
                            
                        </TabPane>
                        <TabPane tab="Videos" key="4">
                        
                        </TabPane>
                        <TabPane tab="Sessions" key="5">
                        
                        </TabPane>
                        <TabPane tab="quizzes" key="6">
                        
                        </TabPane>
                        <TabPane tab="Exams" key="7">
                        
                        </TabPane>
                    </Tabs>
                </main>
                <br/>
                <footer className="Footer">Designed by Eng. Omar Redwan</footer>
            </div>
            )}
    }