Pass props returned by login into props.history.push function

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>

14 thoughts on “Pass props returned by login into props.history.push function”

  1. Modify your Route to <Route path='/pets/:username' component={PetListingComponent} />

    And then you can assess the username in that component using this.props.match.params.username

    I’m saying this from here

    Reply
  2. Solved through doing this:
    Login

     .then(res => {
            if(res.status === 200){
                
                console.log(res);
                props.history.push(`/pets/${state.username}`);
               
            } else {
                const error = new Error(res.error);
                throw error;
            }
    
        })
    

    petlist:

    componentDidMount()
        
    {
        axios.get(`http://localhost:4000/pets/${this.props.match.params.username}`)
        .then((pets)=> {
            this.setState({pets: pet.data})
            
        })
    }
    
    render()
    {
        var pets;
        if(this.state.pets!= null){
            //console.log(this.state.pets)
         tickets = this.state.pets.map(pet=> <div>{pet._id}</div>);
        }
        return(
            <div>
              <ul>{pets}</ul>
            </div>
        )
    }
    
    Reply

Leave a Comment