Answer the question
In order to leave comments, you need to log in
Api request from react application is executed only once, what should I do?
I started to learn react, I decided to write an application that would use a third-party api, I select the data entered in the form (the name of the movie) and pass it with a call to a third-party class to execute the api request, BUT by default there is no movie name and there is Undefined, and he is looking for it, but after changing the name through the form, nothing changes, although the variable that stores the current name changes as it should.
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="title">Enter title</label>
<input id="title" name="title" type="text" />
<button>Send data!</button>
</form>
// тут вызывается класс работающий с api и он не меняется при повоторном сабмите
<FilmDisplay filmName={this.state.res}/>
// название же меняется
{this.state.res}
</div>
);
}
import React from 'react';
class FilmDisplay extends React.Component {
constructor() {
super();
this.state = {
filmData: null
};
}
componentDidMount() {
const filmName = this.props.filmName;
const URL = "http://www.omdbapi.com/?t=" + filmName + "&apikey=6540f2ec&";
console.log(URL);
fetch(URL).then(res => res.json()).then(json => {
this.setState({ filmData: json });
});
}
render() {
const filmData = this.state.filmData;
if (!filmData) return <div>Loading</div>;
return <div>{JSON.stringify(filmData)}</div>;
}
}
export default FilmDisplay;
Answer the question
In order to leave comments, you need to log in
render() {
const { res } = this.state;
const shouldFlimDisplayShown = !!res;
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="title">Enter title</label>
<input id="title" name="title" type="text" />
<button>Send data!</button>
</form>
{shouldFlimDisplayShown && <FilmDisplay filmName={res}/>}
</div>
);
}
import React from 'react';
class FilmDisplay extends React.Component {
constructor() {
super();
this.state = {
filmData: null
};
}
componentDidMount() {
this.fetchMovie();
}
componentDidUpdate(prevProps) {
if (prevProps.filmData !== this.props.filmData) {
this.fetchMovie();
}
}
fetchMovie() {
const { filmName } = this.props;
const URL = "http://www.omdbapi.com/?t=" + filmName + "&apikey=6540f2ec&";
fetch(URL).then(res => res.json()).then(json => {
this.setState({ filmData: json });
});
}
render() {
const { filmData } = this.state;
if (!filmData) return <div>Loading</div>;
return <div>{JSON.stringify(filmData)}</div>;
}
}
export default FilmDisplay;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question