How to pass props returned by a login, into another component's axios get call

I have a React, express, mongo application that I am working on and I am wanting to get the pets for a specific user after they have logged in. I am not sure how I should retrieve the username from the logged in user and then pass it into my PetListing component. I have tried a few things, but I am unsure of what I am doing wrong.

Login component:

    import React, {Component, useState} from 'react';
    const LoginForm = (props) => {
        const [state, setState] = useState({
            username: '',
            password: '',
        });
    
        const onSubmit =(event)=>{
            event.preventDefault();
            fetch('http://localhost:4000/login', {
                method:'POST',
                body: JSON.stringify(state),
                headers:{
                    'Content-Type':'application/json'
                }
            })
            .then(res => {
                if(res.status === 200){
                    props.history.push('/pets');
                    state
                } else {
                    const error = new Error(res.error);
                    throw error;
                }
    
            })
            .catch(err=> {
                console.log(err);
                alert("Error when logging in.")
            })
    
            
        };
       const handleInputChange = (event) => {
            const {value, name} = event.target;
            setState((prevstate)=> ({
                ...prevstate,
                [name]:value
            }));
        };

Pet listing component

    import React from 'react';
    
    
    import axios from 'axios';
    
    export default class PetListing extends React.Component{
        state= {
            username : '',
            pets: []
        }
    
    
        componentDidMount(){
            axios.get(`http://localhost:4000/pets/${this.state.username}`)
            .then(res=>{
                console.log(res);
                console.log(res.data);
            })
        }
    
        render()
    {
        return(
            <ul>
                {this.state.pets.map(tickets => <li>{pets.pet_id}</li>)}
            </ul>
        )
    }
}

App.js

<Nav className="justify-content-end">
              <Nav>
                <Link to={"/pets/{username}"} className="nav-link">
                  View your pets
                </Link>
              </Nav>

9 thoughts on “How to pass props returned by a login, into another component's axios get call”

Leave a Comment