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.