Ajay Singh
Ajay Singh

Reputation: 171

How to pass data returned from server and then transition to another route with returned data?

Hi, I am new to react. I made a server call and then successfully got a response. Now, I am trying to pass the same response to another route and display there. I am unable to understand, how do we do this in react, like in Ember there's a method this.transitionTo('routepath', {data}) and then this data is available in routepath in models(params). How is this possible in react? I am bound to not using any Redux or any other state container. My code is below:

import React, { Component } from 'react'
import axios from 'axios'

class Ernform extends Component {
  constructor (props) {
    super();
    this.state = {
        category: '',
        zipcode: '',
        age: '',
        gender: '',
        key: '',
        data: null
    };
  }

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  }

  getPolicies = (e) => {
    e.preventDefault();
    const { category, zipcode, age, gender, key } = this.state;
    axios.post(`http://localhost:4000/api/v1/quote`, { category, zipcode, age, gender, key })
      .then(response => {
        this.setState({data: response}); // I am setting response from server to the state property data
        this.props.history.push('/details', {data: this.state.data})//I am trying to pass the data and trying to transition here.      
      });
  }

    render() {
    const { category, zipcode, age, gender } = this.state;
        return (
            <div>
                <form onSubmit={this.getPolicies}>
                    <label>
                        Category: <input type="text" name="category" value={category} onChange={this.onChange}/>
                    </label>
                    <label>
                        Zipcode: <input type="text" name="zipcode" value={zipcode} onChange={this.onChange}/>
                    </label>
                    <label>
                        Age: <input type="text" name="age" value={age} onChange={this.onChange}/>
                    </label>
                    <label>
                        Gender: <input type="text" name="gender" value={gender} onChange={this.onChange}/>
                    </label>
          <button className="btn btn-primary btn-lg lead" type="submit">Get Policies</button>
                </form>
            </div>
        );
    }
}

export default Ernform

My router is this:

import React from 'react'
import { Switch, Route } from 'react-router-dom'
import Ernform from './Ernform';
import Ernentry from './Ernentry'
import Erndetails from './Erndetails';

const Routing = () => (
    <main>
      <Switch>
        <Route exact path='/' component={Ernentry}/>
        <Route path='/auto' component={Ernform}/>
        <Route path='/life' component={Ernform}/>
        <Route path='/details' component={Erndetails}/> // added this route.
      </Switch>
    </main>
  )

  export default Routing

My details route component is this

import React, { Component } from 'react'


class Erndetails extends Component {
    constructor(props) { // Where would i get the data i transition with from that route.
        console.log(props);
        super()
    }
    render() {
        return (
            <div></div>
        )
    }
}

export default Erndetails

Thanks a lot guys in Advance.

Upvotes: 0

Views: 130

Answers (2)

Sulokit
Sulokit

Reputation: 137

There are two solutions for your problem,

I) First solution is to pass the data in the push object along with the route in this manner, this.props.history.push({ pathname: '/details', state: { detail: response.data } })

instead of what your passing.

In your details route component you can get fetch the data by using props.location.state.detail in your constructor or this.props.location.state.detail in componentDidMount life-cycle.

2) Second solution would be the store it in the local-storage using localStorage.setItem('token', data) and then access it using localStorage.getItem('token')

Upvotes: 1

mcssym
mcssym

Reputation: 944

I don’t think react-router allows it. My advise will be to store your data in LocalStorage with LocalStorage#setItem method and after in your next component retrieve it with LocalStorage#getItem.

You can also use Redux for your state and share data with it between screen but as you are beginner it’ll take you more time to learn it.

You can also use Context API of React but as Redux it’ll take you more time even if it is easier than Redux.

Upvotes: 0

Related Questions