I am creating a React Application for searching for movies using the OMDb.
My app works in two stages:
- You are presented initially with a search box
- Upon submitting the search box with a movie query, the app should redirect to a results page.
Below is my Main application:
class Muuvies extends Component {
constructor() {
super();
this.state ={
movies: [],
error: "",
searchedFor: "",
};
this.search = this.search.bind(this);
}
search({data}) {
fetch(`http://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${data}&type=movie`)
.then(res => res.json())
.then(res => {
return res;
}).then(json => this.setState({
searchedFor: data,
movies: propOr([], 'Search', json),
error: json.Error
})).catch(err => this.setState({
error: 'Error Occurred: Try Again',
movies: [],
searchedFor: ''
}));
// if there wasn't an error, redirect to the Results page, passing what is returned from fetch().
}
render() {
return (
<Container>
<Logo role="img" aria-label="search">🍿</Logo>
<SearchWrapper>
<Search search={this.search} />
{
this.state.error
? <Error><span role="img" aria-label="error" style={{marginRight: 2 + 'px'}}>⚠️</span>{this.state.error}</Error>
: null
}
</SearchWrapper>
</Container>
);
}
}
How do I change my application so, that if the user submits the form and there isn't an error (e.g. this.state.error is empty after the fetch()), then it redirects them to the Results component?
Contents of Search.js:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
data: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
this.props.search(this.state);
this.setState({ data: '' });
}
render () {
return (
<StyledForm onSubmit={this.handleSubmit}>
<StyledSearch id="data" type="text"
name="data"
placeholder="Search for Muuvies."
value={path(['state', 'data'], this)}
onChange={this.handleChange}
autoComplete="off"
autoFocus={true}
/>
</StyledForm>
)
}
}
push()than you can use to programatically navigate.historyshould be available on the component's props.You'd need to use withRouter to access this.if (!this.state.error) this.props.history.push(Results)?then()?resultsto be its own separate route. What is the point of that? Typically, you would not want a route in your application to depend upon the prior state of your app. What happens if someone goes directly to theresultsroute of your app without having done a search? If you can't send someone a URL to aresultsroute and have them do anything useful there, what is the point? Instead, maybe have just thesearchroute and render the results there as needed.statewill be lost? What will they see when they return to the bookmark and how will it be useful to them?"