0
votes

I've been having a problem with React Route. I can pass pass2Parent={this.pass2Parent} to the Search component, but I can't pass data={data} to the Result component.

I've been researching the problem for hours and I've explored using render instead of component in the route. Unfortunately, it had the side effect of calling an API multiple times and burning through my allowance.

I just don't get why it's not working as it is..

render() {
  let data = this.state;
  console.log(data);

  return (
    <div style={{height: "inherit"}}>
      <BrowserRouter>
        <Switch>
          <Route path='/' exact component={() => <Search pass2Parent={this.pass2Parent}/>}/>
          <Route path='/result' exact component={(data) => <Result data={data}/>}/>
        </Switch>
      </BrowserRouter>
    </div>
  );
};

This is what console.log(data) returns:

{
  images: {total: 8327, total_pages: 833, results: Array(10)},
  weather: {coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
}

This is what console.log(this.props) looks like in the child component:

{
  data: {
    history: {length: 2, action: "POP", location: {…}, createHref: ƒ, push: ƒ, …},
    location: { pathname: "/result", search: "", hash: "", state: undefined },
    match: { path: "/result", url: "/result", isExact: true, params: {…} },
    staticContext: undefined,
  }
}
1
By specifying a data argument to your inline component you're shadowing the local data variable. Inside your inline component, the props object is called "data". Omit the data argument: component={() => <Result data={data} /> - ray hatfield
When does the data become available? Is it immediately available on render of the <Result /> component? Or is it fetched later? - Seth Lutske
@rayhatfield I just changed it to <Route path='/result' exact component={() => <Result data={this.state}/>}/>,The same issue came up, that in the child component. console.log(this.props) --> {data: {…}} data: proto: Object proto: Object - Steven

1 Answers

1
votes

the argument data passed into your component={(data)=> is a SyntheticEvent, that inside it scope overwrite the data value from state. Delete the argument and that it...


<Route path='/result' exact component={() => <Result data={data}/>}/>