0

I have Tenant component which is responsible for listing all tenant details eg: Name,Phone,Rent etc and i have AddTenant component which contain a form that is used to create new tenant.

In my AddTenant component i make an api call to store the new tenant info in the database,after successfull api call i want to redirect to Tenant component and want to show an alert (this alert message should be shown on condition)

So far i am able to make an api call and can redirect to Tenant component using react-router redirect component but unable to show the alert message on condition

Tenant Component

export default class Tenant extends React.Component {
    constructor(){
        super();
        this.state = {
            tenantList:[],
        }
    }

    componentDidMount(){
        
        axios.get("http://127.0.0.1:8000/api/tenants").then(response => {
            this.setState({
              tenantList: [...response.data.tenants]
            })

          })
      
    }

    render() {
        const {tenantList} = this.state

        // show alert on conditon
        var alert = ''
        if(this.props.location.state!==undefined){
            alert = <div class="alert alert-success" role="alert">
                        Success       
                    </div>
            const {location,history} = this.props;
            history.replace()
        }
        
      return (
        <div>
          {/** show alert here*/}
        </div>
          
      );
    }
}

AddTenant Component

export default class AddTenant extends React.Component {
    constructor(props) {
        super(props);
        this.state ={
            startDate: moment(),
            nameInput: '',
            nidInput:'',
            nid_img:'',
            phoneInput:'',
            rentInput:'',
            hridInput:'',
            nameError: '',
            nidError:'',
            phoneError:'',
            rentError:'',
            hridError:'',
            errors:'',
            msg:'',
            redirect:false
        }
    }

    handleDateChange = (date)=>{
        this.setState({
            startDate: date
          })
        
    }
    handleFieldChange = (e)=>{ 
        this.setState({
            [e.target.name] : e.target.value
        })
        
    }
    handleDropDownMenu = (hridInput)=>{
        this.setState({ hridInput });
        console.log(`Option selected:`, hridInput);
    }

    validate = ()=>{
        let flag = true;
        let nameError = ""
        let hridError = ""

        if(!this.state.nameInput.includes(' ')){
            nameError = "Full name should contain a space"
            this.setState({nameError})
            flag = false
        }
        
        if(this.state.hridInput.value === undefined){
            hridError = "please select a house/room number"
            this.setState({hridError})
            flag = false
        }

        //datepicker validation is not done

        return flag

    }
    

    handleFormSubmit = (e)=>{
        e.preventDefault();
        
        let isValid = this.validate()

        if(isValid){
            console.log("form valid")
            const tenant = {
                name: this.state.nameInput,
                nid:this.state.nidInput,
                phone:this.state.phoneInput,
                exp_rent: this.state.rentInput,
                reg_date:moment(this.state.startDate).format("YYYY-MM-DD"),
                hrid:this.state.hridInput.value
            }
            //below line is commented because to test redirect component
            //console.log(tenant)
            // axios.post('http://127.0.0.1:8000/api/tenants', tenant)
            // .then(response => {
            //     // redirect to the homepage
            //     this.setState({redirect:true,msg:'success'})
            //     console.log(response);
                
            // })
            // .catch(error => {
            //     this.setState({
            //     errors: error.response.data.errors,msg:'failed'
            //     })
            // })
            this.setState({redirect:true,msg:'success'})
            this.setState({nameError:'',hridError:''})
        }
    }

    render() {
        if(this.state.redirect){
            return <Redirect to={{
                pathname: "/tenant",
                state : {msg:this.state.msg}
            }}/>
        }
      return (
        <div>
            <AddTenantForm />
        </div>
      );
    }
}
mirsahib
  • 375
  • 1
  • 4
  • 12

1 Answers1

0

You can pass parameters with redirect.

render() {
    if(this.state.redirect){
        return <Redirect to={{
            pathname: "/tenant",
            state : {msg:this.state.msg, yourCondition : 
                     this.state.yourCondition}
        }}/>
    }

And update yourCondition state when you are updating state.redirect:

this.setState({redirect:true,msg:'success'})
this.setState({nameError:'',hridError:''})
this.setState({yourCondition : yourCondition)

In Tenants component:

    // show alert on conditon
    var alert = ''
    if(this.props.location.state!==undefined){
        if(this.props.location.yourCondition) {
           alert = <div class="alert alert-success" role="alert">
                    Success       
                   </div>
           const {location,history} = this.props;
           history.replace()
        }
    }
Çağatay Sel
  • 801
  • 7
  • 14
  • this.props.location.state.msg is undefined when i try to place this code inside any div in tenant component – mirsahib Jul 09 '20 at 15:13
  • Could you console.log(this.props.location.state) and check what is in state. Also can you replace {msg : this.state.msg} with {msg : "dummy"} to check if this.state.msg is undefined at redirect. – Çağatay Sel Jul 09 '20 at 15:22
  • for a fresh restart (npm run start) the state show undefined but after i fill the form and redirect to Tenant component it shows an object with msg attribute ,here is another problem i can't delete the this.props.location.state.msg which make the alert to stay even though i have refresh the page or come from another page – mirsahib Jul 10 '20 at 01:21
  • It is expected that msg will be undefined if you directly open the page since you add msg while routing from AddTenants. To clear location you can check the answer in this link : https://stackoverflow.com/questions/40099431/how-do-i-clear-location-state-in-react-router-on-page-reload – Çağatay Sel Jul 10 '20 at 04:30
  • the page break when msg is undefined what should i do to avoid that,i have tried enclosing this.props.location.state.msg!==undefined in if statement but it doesn't help – mirsahib Jul 10 '20 at 04:40