0

Expected: On every page, I have a search form. When submitted, it will show the fetched data.

Occurs: When I submit the form, I receive a TypeError: dataItems is undefined

Here's my app component

class App extends Component {
  render() {
    return (
      <Router>
        <ThemeProvider theme={theme}>
          <AppWrapper>
            <Header />
            <Switch>
              <Route path='/' exact component={HomePage} />
              <Route path='/searched-anime' exact component={AnimeCard} />
              <Route path='/:animeId' exact component={AnimeDetails} />
            </Switch>
          </AppWrapper>
        </ThemeProvider>
      </Router>
    );
  }
}

Here's my form AnimeSearchForm

class AnimeSearchForm extends Component {
  state = {
    dataItems: [],
    animeSearched: false,
    topAni: null
  }

  handleButtonSearch = async (e) => {
    e.preventDefault()

    const animeQuery = e.target.elements.anime.value
    const response = await fetch(`${API}/search/anime?q=${animeQuery}&page=1`)
    const response2 = await fetch(`${API}/top/anime/1/movie`)

    const animeData = await response.json()
    const topAnime = await response2.json()

    this.setState({
      anime: !this.state.animeSearched,
      dataItems: animeData.results,
      topAni: topAnime.top
    })
  }

  render() {
    const { dataItems, topAnime, anime } = this.state

    return (
      <div>
        <Form handleButtonSearch={this.handleButtonSearch} />
        {anime
          ?
          <AnimeCard
            dataItems={dataItems}
            topAni={topAnime}
          />
          : null}
        {dataItems.length > 0 &&
          <Redirect to={{
            pathname: '/searched-anime',
            state: { dataItems: this.state.dataItems }
          }} />
        }
      </div>
    )
  }
}

And my component to be rendered AnimeCard

const AnimeCard = ({ dataItems }) => {
  return (
    <AnimeCardWrapper>
      {dataItems
        .filter(item => item.rated !== 'Rx' && item.score !== 0 && item.type === 'TV') // filter out adult content
        .map(item => {
          return (
            <Card key={item.mal_id}>
              <Poster>
                <PosterImg src={item.image_url} alt="poster" />
              </Poster>

              <Title>{item.title}</Title>

              <Info>
                <Score>{item.score}</Score>
                <Rating>{item.rated}</Rating>
              </Info>
            </Card>
          )
        })}
    </AnimeCardWrapper>
  );
}

I attempted to use the history API from React Router and my component rendered, but it would render with whatever component I was on at the given time. i.e I would search on the homepage and the search results would appear on the homepage with all of the homepage content. So I tried using redirect and ended up with this issue.

I referred to this post to get me rolling but to no avail.

Dave.Q
  • 309
  • 2
  • 16
  • Did you try 'dataItems' instead of this.state.dataItems? – Sujoy Nov 02 '19 at 04:16
  • for your code to work anime data should be a object with a array named response . try to make it sure by `console.log(animeData)` . – nir99 Nov 02 '19 at 05:40

1 Answers1

1

As you are using <Redirect /> component with a state object.

<Redirect to={{
            pathname: '/searched-anime',
            state: { dataItems: this.state.dataItems }
          }} />

It is available as props.location.state in the target (redirected to) component

As per the docs

The state object can be accessed via this.props.location.state in the redirected-to component. This new referrer key (which is not a special name) would then be accessed via this.props.location.state.referrer in the Login component pointed to by the pathname '/login'

You have to change <AnimeCard /> component to...

const AnimeCard = ({ location }) => {
  const {dataItems} = location.state;
  return (
    <AnimeCardWrapper>
      {dataItems
        .filter(item => item.rated !== 'Rx' && item.score !== 0 && item.type === 'TV') // filter out adult content
        .map(item => {
          return (
            <Card key={item.mal_id}>
              <Poster>
                <PosterImg src={item.image_url} alt="poster" />
              </Poster>

              <Title>{item.title}</Title>

              <Info>
                <Score>{item.score}</Score>
                <Rating>{item.rated}</Rating>
              </Info>
            </Card>
          )
        })}
    </AnimeCardWrapper>
  );
}
Nithin Thampi
  • 3,001
  • 1
  • 10
  • 9