Alex Erling
Alex Erling

Reputation: 307

How do I send an object through history.push to the page I'm redirected to | REACT

I have an object (results) from a search bar, I'm trying to send through history.push to the search results page, I'm having trouble being able to access the object through props on the page I'm redirected to. What's the easiest way for me to get redirected to the next page and be able to access the results I'm trying to send there.

import React, {Component} from 'react';
import {Search, List, Form} from 'semantic-ui-react';
import {browserHistory,withRouter} from "react-router-dom"
import axios from 'axios';

class SearchBar extends Component {
  constructor(props) {
    super(props)
    this.state = {query: '', results: [], isLoading: false}
  }

  componentWillMount() {
     this.resetComponent()
   }

   resetComponent = () => this.setState({ isLoading: false, results: [], query: '' })

   search(query) {
     this.setState({ query });
     axios
       .get(`/api/search?query=${query}`)
       .then(response => {
         this.setState({ results: response.data});
       })
       .catch(error => console.log(error));
   }

   handleFormSubmit = () => {
   console.log('search:', this.state.query);
   this.props.action
   this.props.history.push({pathname: `/search/${this.state.query}`, results: `${this.state.results}`})
   this.resetComponent()



 }


  handleInputChange = (query) => {
    this.search(query);
    this.setState({ isLoading: true, query })

    setTimeout(() =>
      this.setState({
        isLoading: false,
      }) , 300)

  }

  handleResultSelect = (e, { result }) => this.setState({ query: result.title}  )

  render () {

    const resultRenderer = ({ title }) => <List content = {title}/>
    return (

      <Form onSubmit={this.handleFormSubmit}>
      <Search
        loading={this.state.isLoading}
        onResultSelect={this.handleResultSelect}
        onSearchChange={(event) => {this.handleInputChange(event.target.value)}}
        showNoResults={false}
        value={this.state.query}
        resultRenderer={resultRenderer}
        results ={this.state.results}
        type={"submit"}
        { ...this.props}  />
      </Form>

    );
  }

}


export default withRouter (SearchBar)

Upvotes: 0

Views: 1197

Answers (2)

SrThompson
SrThompson

Reputation: 5748

You can use history.push in 2 ways: with 2 arguments, a path and an optional state history.push(path, [state]) or a location object that contains one or more of the properties {pathname, search, hash, state}. Either way you do it, the way that you send custom data to the next location is through the location object's state. You're already close, just change this line:

this.props.history.push({pathname: `/search/${this.state.query}`, results: `${this.state.results}`})

To this

this.props.history.push({pathname: `/search/${this.state.query}`, state: {results: `${this.state.results}`}})

Then you can access the data in your next component throgh props.location.state

Upvotes: 2

Dat Tran
Dat Tran

Reputation: 1586

The best way is to use state container for react. There are several library for that, but Redux is the most common thing working together with react.

The idea is to keep your data of react application centralized in one place, so that you can access it everywhere in the application.

Redux is a predictable state container for JavaScript apps. (Not to be confused with a WordPress framework – Redux Framework.)

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

You can also visit some tutorial to get started with it: https://medium.com/@notrab/getting-started-with-create-react-app-redux-react-router-redux-thunk-d6a19259f71f

Ref: https://redux.js.org/

Upvotes: 0

Related Questions