Reputation: 57
i am using react and next.js for making API request(from search bar) and displaying the list of movies on the homepage and every search result will take me to a different page,which will show data related to that movie. Every time when i refresh the details page then the result of query is lost due to which wrong api request is made and search results are also lost when i use backwards/forward button.
index.js
<Link href={`/Details?id=${movie.imdbID}`}> //code to take me to the Details page
Details.js
const Details =()=>{
const router = useRouter();
let [result,setResult]=useState({});
const query=router.query.id; //storing the id from the URL
useEffect(() => {
axios.get('http://www.omdbapi.com/?',
{params:{
apikey:'',
i:query,
plot:'full'
}
}).then(response=> setResult(response.data))
}, []);
return <SearchBar />
} export default Details;
also i have implemented a Searchbar component used it in the index.js which works fine.i wish to use the same component in the details.js file to avoid code redundancy but i dont know the correct approach.
index.js
<SearchBar whenSubmit={this.onSearchSubmit}/>
SearchBar.js
onFormSubmit=(event)=>{
event.preventDefault();
this.props.whenSubmit(this.state.term);
}
render(){
<form className="ui form" onSubmit={this.onFormSubmit}>
<input type="text" value={this.state.term} placeholder="search any movie"
onChange={event=>this.setState({term: event.target.value})} />
</form>}
Upvotes: 0
Views: 1249
Reputation: 11610
If you read the docs, you'll find that:
Note: Pages that are statically optimized by automatic static optimization will be hydrated without their route parameters provided (query will be empty, i.e. {}). After hydration, Next.js will trigger an update to your application to provide the route parameters in the query object. If your application cannot tolerate this behavior, you can opt-out of static optimization by capturing the query parameter in getInitialProps.
So, the solution is to add getInitialProps
to your component:
Details.getInitialProps = async () => ({});
export default Details;
Or change useEffect
to fetch data only when id
is available:
useEffect(() => {
if (query) {
axios
.get("http://www.omdbapi.com/?", {
params: {
apikey: "",
i: query,
plot: "full"
}
})
.then(response => setResult(response.data));
}
}, [query]);
Upvotes: 2
Reputation: 334
As i can observe your code you are using query param which will lost your querystring value every reload or can say backward and forward. you can try path_param instead of query_param.
<Route path="/Details/:id" component={MovieDetailsComponent} exact></Route>
<Link to={
/movies/${id}}>
movies details page parseInt(props.match.params.id);
i used this approach to fetch data from server in useEffect and it's working fine for me you can try also.
Upvotes: 0