0

I want the results of an api call to be shown on an '/events' page. I've tried using Redirect from react-router-dom but this only redirects the page.

I have tried looking at this answer

How can I on Submit my Form redirect the Results to another Page in React

But am unsure how this could apply to my code. If I use this.props.history.push('/events') I get an error message saying it doesn't recognize .push.

Would be grateful if someone can put me on the right course.

import React, {Component} from 'react';
import axios from 'axios';
import {Form, FormControl, Button}  from 'react-bootstrap';
import './style.css';


class SearchField extends Component {

    state = {
        search: ""
    };


    handleChange = (event) => {
        const {name, value} = event.target;
        this.setState({[name]: value.toLowerCase()});
    };


    apiCall = () =>{

        const corsAnywhere = "https://cors-anywhere.herokuapp.com/";
        const ticketmasterURL = "https://app.ticketmaster.com/discovery/v2/events/?keyword=";
        const searchKey = process.env.REACT_APP_TM_KEY;
        const term = this.state.search.split(" ").join("+");


        axios.get(corsAnywhere + ticketmasterURL + term + "&apikey=" + searchKey)
        .then(res => {
            console.log(res.data._embedded.events);
            this.history.push("/events");
        })
        .catch(err => console.log(err));
    };


    handleSubmit = (event) => {
        event.preventDefault();
        this.apiCall();
    };


    render(){
        return (
            <div className="search-container">
                <Form onSubmit={this.handleSubmit}>
                    <Form.Group>
                        <FormControl 
                            type="text" 
                            placeholder="Search" 
                            name="search"
                            value={this.state.search} 
                            onChange={this.handleChange}
                        />
                        <div className="btn-container">
                            <Button type="submit">Submit</Button>
                        </div>
                    </Form.Group>
                </Form>
            </div>
        )
    }

}


export default SearchField;


szewah
  • 137
  • 2
  • 15

1 Answers1

1

When you use this.props.history.push('/events'), you are getting error.

Because to work with history object you need to wrap your component using withRouter HOC.

import { withRouter } from 'react-router-dom';

class SearchField extends Component { ... }

export default withRouter(SearchField)

Now you can use history object to sent data,

axios.get(corsAnywhere + ticketmasterURL + term + "&apikey=" + searchKey)
    .then(res => {
      console.log(res.data._embedded.events);

      this.props.history.push({
        pathname: '/events',
        state: { events_data: JSON.stringify(res.data._embedded.events) }
      })

    })

In events component you can access the data like,

render(){
    const events_data = JSON.parse(this.props.location.state.events_data)
    console.log(events_data)

    return( ... )
}

You can make use of Redirect from react-router-dom package to send data as well.

axios.get(corsAnywhere + ticketmasterURL + term + "&apikey=" + searchKey)
    .then(res => {
      console.log(res.data._embedded.events);

      <Redirect 
         to={{
            pathname: '/events',
            state: { events_data: JSON.stringify(res.data._embedded.events) }
         }}
      />
    })

In events component you can access the data like,

render(){
    const events_data = JSON.parse(this.props.location.state.events_data)
    console.log(events_data)

    return( ... )
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
  • 1
    WithRouter worked for me. Big thanks. For Redirect, I had problems with rendering the events page. – szewah Sep 07 '19 at 12:32
  • I am having problems with showing the results of the page. After adding those two lines const events_data = JSON.parse(this.props.location.state.events_data) console.log(events_data) I get TypeError: Cannot read property 'state' of undefined Would you know why this might be? – szewah Sep 09 '19 at 15:34
  • I think you are not getting API response. – ravibagul91 Sep 09 '19 at 15:37
  • I can see the api response on the search page if I console log it. And when I look at the history prop, it shows the state. It's when I console.log this.props in the events page, I get undefined. – szewah Sep 09 '19 at 16:00
  • Did you wrap your events component using `withRouter`? – ravibagul91 Sep 09 '19 at 16:03
  • 1
    I'm sorry, I quite new to react: would that be to wrap it like this? export default withRouter(EventListing)? – szewah Sep 09 '19 at 16:42
  • 1
    I sort of have it working. I had to pull out location, match, and history and assign it to a variable. It wouldn't just work as this.props.location.state. – szewah Sep 09 '19 at 17:56