Re-render React component back to original state












1















I have this component that returns a bunch of li's on a axios get request, users input text and the search is updated..I want React to re-render the component when the searchInput is null, basically back to its original state.



  class App extends Component {
constructor (props) {
super(props)
this.state = {
searchResults: , // API Call returns an array of results
searchInput: '', // Search Term for API Call
searchImage: //base_url, a file_size and a file_path.
}
}


performSearch = () => { // Requesting data from API
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
this.setState({ searchResults: res.data.results});
});
}


This function below is what triggers the rendering



   handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
} else if (this.state.searchInput && this.state.searchInput.length === 0 ) {
return ({ searchResults: null})
}
}
});
}




import React from 'react'

const Suggestions = (props) => {
const options = props.searchResults.map(r => (
<li
key={r.id} >
<img src={`https://image.tmdb.org/t/p/w185/${r.poster_path}`} alt={r.title} />
<a href='#t' className='rating'><i className='fas fa-star fa-fw' />{r.vote_average}</a>
</li>
))
return <ul className='search-results'>{options}</ul>
}

export default Suggestions


Issue at the moment is that is that if I search something, eg 'game of thrones' it renders the li's, however if I clear it back to an empty string, I still have left over li's...I dont't wanna see anything if the searchInput is null



Edit: performSearch is fires again while clearing searchInput and returns the last two characters which leaves me with left over li's










share|improve this question

























  • set the searchResults to an empty array when the value of searchInput is empty. Also, the length check is not required as empty string is false

    – klvenky
    Nov 23 '18 at 6:43











  • Still doesnt work, I've tried the solution below too

    – invrt
    Nov 23 '18 at 6:52
















1















I have this component that returns a bunch of li's on a axios get request, users input text and the search is updated..I want React to re-render the component when the searchInput is null, basically back to its original state.



  class App extends Component {
constructor (props) {
super(props)
this.state = {
searchResults: , // API Call returns an array of results
searchInput: '', // Search Term for API Call
searchImage: //base_url, a file_size and a file_path.
}
}


performSearch = () => { // Requesting data from API
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
this.setState({ searchResults: res.data.results});
});
}


This function below is what triggers the rendering



   handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
} else if (this.state.searchInput && this.state.searchInput.length === 0 ) {
return ({ searchResults: null})
}
}
});
}




import React from 'react'

const Suggestions = (props) => {
const options = props.searchResults.map(r => (
<li
key={r.id} >
<img src={`https://image.tmdb.org/t/p/w185/${r.poster_path}`} alt={r.title} />
<a href='#t' className='rating'><i className='fas fa-star fa-fw' />{r.vote_average}</a>
</li>
))
return <ul className='search-results'>{options}</ul>
}

export default Suggestions


Issue at the moment is that is that if I search something, eg 'game of thrones' it renders the li's, however if I clear it back to an empty string, I still have left over li's...I dont't wanna see anything if the searchInput is null



Edit: performSearch is fires again while clearing searchInput and returns the last two characters which leaves me with left over li's










share|improve this question

























  • set the searchResults to an empty array when the value of searchInput is empty. Also, the length check is not required as empty string is false

    – klvenky
    Nov 23 '18 at 6:43











  • Still doesnt work, I've tried the solution below too

    – invrt
    Nov 23 '18 at 6:52














1












1








1








I have this component that returns a bunch of li's on a axios get request, users input text and the search is updated..I want React to re-render the component when the searchInput is null, basically back to its original state.



  class App extends Component {
constructor (props) {
super(props)
this.state = {
searchResults: , // API Call returns an array of results
searchInput: '', // Search Term for API Call
searchImage: //base_url, a file_size and a file_path.
}
}


performSearch = () => { // Requesting data from API
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
this.setState({ searchResults: res.data.results});
});
}


This function below is what triggers the rendering



   handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
} else if (this.state.searchInput && this.state.searchInput.length === 0 ) {
return ({ searchResults: null})
}
}
});
}




import React from 'react'

const Suggestions = (props) => {
const options = props.searchResults.map(r => (
<li
key={r.id} >
<img src={`https://image.tmdb.org/t/p/w185/${r.poster_path}`} alt={r.title} />
<a href='#t' className='rating'><i className='fas fa-star fa-fw' />{r.vote_average}</a>
</li>
))
return <ul className='search-results'>{options}</ul>
}

export default Suggestions


Issue at the moment is that is that if I search something, eg 'game of thrones' it renders the li's, however if I clear it back to an empty string, I still have left over li's...I dont't wanna see anything if the searchInput is null



Edit: performSearch is fires again while clearing searchInput and returns the last two characters which leaves me with left over li's










share|improve this question
















I have this component that returns a bunch of li's on a axios get request, users input text and the search is updated..I want React to re-render the component when the searchInput is null, basically back to its original state.



  class App extends Component {
constructor (props) {
super(props)
this.state = {
searchResults: , // API Call returns an array of results
searchInput: '', // Search Term for API Call
searchImage: //base_url, a file_size and a file_path.
}
}


performSearch = () => { // Requesting data from API
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
this.setState({ searchResults: res.data.results});
});
}


This function below is what triggers the rendering



   handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
} else if (this.state.searchInput && this.state.searchInput.length === 0 ) {
return ({ searchResults: null})
}
}
});
}




import React from 'react'

const Suggestions = (props) => {
const options = props.searchResults.map(r => (
<li
key={r.id} >
<img src={`https://image.tmdb.org/t/p/w185/${r.poster_path}`} alt={r.title} />
<a href='#t' className='rating'><i className='fas fa-star fa-fw' />{r.vote_average}</a>
</li>
))
return <ul className='search-results'>{options}</ul>
}

export default Suggestions


Issue at the moment is that is that if I search something, eg 'game of thrones' it renders the li's, however if I clear it back to an empty string, I still have left over li's...I dont't wanna see anything if the searchInput is null



Edit: performSearch is fires again while clearing searchInput and returns the last two characters which leaves me with left over li's







javascript reactjs ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 7:53







invrt

















asked Nov 23 '18 at 6:38









invrtinvrt

628




628













  • set the searchResults to an empty array when the value of searchInput is empty. Also, the length check is not required as empty string is false

    – klvenky
    Nov 23 '18 at 6:43











  • Still doesnt work, I've tried the solution below too

    – invrt
    Nov 23 '18 at 6:52



















  • set the searchResults to an empty array when the value of searchInput is empty. Also, the length check is not required as empty string is false

    – klvenky
    Nov 23 '18 at 6:43











  • Still doesnt work, I've tried the solution below too

    – invrt
    Nov 23 '18 at 6:52

















set the searchResults to an empty array when the value of searchInput is empty. Also, the length check is not required as empty string is false

– klvenky
Nov 23 '18 at 6:43





set the searchResults to an empty array when the value of searchInput is empty. Also, the length check is not required as empty string is false

– klvenky
Nov 23 '18 at 6:43













Still doesnt work, I've tried the solution below too

– invrt
Nov 23 '18 at 6:52





Still doesnt work, I've tried the solution below too

– invrt
Nov 23 '18 at 6:52












1 Answer
1






active

oldest

votes


















1














You haven't handled the conditions correct in the handleInputChange method. If the outer condition fails, the inner won't ever execute



 handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
}
} else {
this.now = Date.now();
this.setState({ searchResults: })
}
});
}


Also the issue here could possible be the race condition with the API calls. It might so happen that when you clear the input although you setState to null or empty, the API then responds which sets the state again. The best way to handle is to accept only response that corresponds to the last request made



performSearch = () => { // Requesting data from API
let now = (this.now = Date.now());
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
// Accepting response if this request was the last request made
if (now === this.now) {
this.setState({ searchResults: res.data.results});
}
});
}





share|improve this answer


























  • Still have left over li's

    – invrt
    Nov 23 '18 at 6:52











  • How are you rendering the list elements

    – Shubham Khatri
    Nov 23 '18 at 6:53











  • <div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

    – invrt
    Nov 23 '18 at 7:03











  • Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

    – Shubham Khatri
    Nov 23 '18 at 7:12













  • It's a custom component, i've updated original post, and I've tried the empty array too

    – invrt
    Nov 23 '18 at 7:19











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53441714%2fre-render-react-component-back-to-original-state%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You haven't handled the conditions correct in the handleInputChange method. If the outer condition fails, the inner won't ever execute



 handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
}
} else {
this.now = Date.now();
this.setState({ searchResults: })
}
});
}


Also the issue here could possible be the race condition with the API calls. It might so happen that when you clear the input although you setState to null or empty, the API then responds which sets the state again. The best way to handle is to accept only response that corresponds to the last request made



performSearch = () => { // Requesting data from API
let now = (this.now = Date.now());
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
// Accepting response if this request was the last request made
if (now === this.now) {
this.setState({ searchResults: res.data.results});
}
});
}





share|improve this answer


























  • Still have left over li's

    – invrt
    Nov 23 '18 at 6:52











  • How are you rendering the list elements

    – Shubham Khatri
    Nov 23 '18 at 6:53











  • <div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

    – invrt
    Nov 23 '18 at 7:03











  • Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

    – Shubham Khatri
    Nov 23 '18 at 7:12













  • It's a custom component, i've updated original post, and I've tried the empty array too

    – invrt
    Nov 23 '18 at 7:19
















1














You haven't handled the conditions correct in the handleInputChange method. If the outer condition fails, the inner won't ever execute



 handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
}
} else {
this.now = Date.now();
this.setState({ searchResults: })
}
});
}


Also the issue here could possible be the race condition with the API calls. It might so happen that when you clear the input although you setState to null or empty, the API then responds which sets the state again. The best way to handle is to accept only response that corresponds to the last request made



performSearch = () => { // Requesting data from API
let now = (this.now = Date.now());
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
// Accepting response if this request was the last request made
if (now === this.now) {
this.setState({ searchResults: res.data.results});
}
});
}





share|improve this answer


























  • Still have left over li's

    – invrt
    Nov 23 '18 at 6:52











  • How are you rendering the list elements

    – Shubham Khatri
    Nov 23 '18 at 6:53











  • <div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

    – invrt
    Nov 23 '18 at 7:03











  • Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

    – Shubham Khatri
    Nov 23 '18 at 7:12













  • It's a custom component, i've updated original post, and I've tried the empty array too

    – invrt
    Nov 23 '18 at 7:19














1












1








1







You haven't handled the conditions correct in the handleInputChange method. If the outer condition fails, the inner won't ever execute



 handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
}
} else {
this.now = Date.now();
this.setState({ searchResults: })
}
});
}


Also the issue here could possible be the race condition with the API calls. It might so happen that when you clear the input although you setState to null or empty, the API then responds which sets the state again. The best way to handle is to accept only response that corresponds to the last request made



performSearch = () => { // Requesting data from API
let now = (this.now = Date.now());
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
// Accepting response if this request was the last request made
if (now === this.now) {
this.setState({ searchResults: res.data.results});
}
});
}





share|improve this answer















You haven't handled the conditions correct in the handleInputChange method. If the outer condition fails, the inner won't ever execute



 handleInputChange = () => {
this.setState({
searchInput: this.search.value // User input
}, () => {
if (this.state.searchInput && this.state.searchInput.length >1 ) {
if (this.state.searchInput.length % 2 === 0) { // Request data on user input
this.performSearch();
}
} else {
this.now = Date.now();
this.setState({ searchResults: })
}
});
}


Also the issue here could possible be the race condition with the API calls. It might so happen that when you clear the input although you setState to null or empty, the API then responds which sets the state again. The best way to handle is to accept only response that corresponds to the last request made



performSearch = () => { // Requesting data from API
let now = (this.now = Date.now());
axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
.then((res) => {
console.log(res.data.results);
// Accepting response if this request was the last request made
if (now === this.now) {
this.setState({ searchResults: res.data.results});
}
});
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 23 '18 at 8:33

























answered Nov 23 '18 at 6:44









Shubham KhatriShubham Khatri

93.8k15118158




93.8k15118158













  • Still have left over li's

    – invrt
    Nov 23 '18 at 6:52











  • How are you rendering the list elements

    – Shubham Khatri
    Nov 23 '18 at 6:53











  • <div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

    – invrt
    Nov 23 '18 at 7:03











  • Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

    – Shubham Khatri
    Nov 23 '18 at 7:12













  • It's a custom component, i've updated original post, and I've tried the empty array too

    – invrt
    Nov 23 '18 at 7:19



















  • Still have left over li's

    – invrt
    Nov 23 '18 at 6:52











  • How are you rendering the list elements

    – Shubham Khatri
    Nov 23 '18 at 6:53











  • <div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

    – invrt
    Nov 23 '18 at 7:03











  • Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

    – Shubham Khatri
    Nov 23 '18 at 7:12













  • It's a custom component, i've updated original post, and I've tried the empty array too

    – invrt
    Nov 23 '18 at 7:19

















Still have left over li's

– invrt
Nov 23 '18 at 6:52





Still have left over li's

– invrt
Nov 23 '18 at 6:52













How are you rendering the list elements

– Shubham Khatri
Nov 23 '18 at 6:53





How are you rendering the list elements

– Shubham Khatri
Nov 23 '18 at 6:53













<div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

– invrt
Nov 23 '18 at 7:03





<div className='search-results-div'> <Suggestions searchResults={this.state.searchResults} /> </div>

– invrt
Nov 23 '18 at 7:03













Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

– Shubham Khatri
Nov 23 '18 at 7:12







Is suggestion your custom component or some library. Probably instead of null, you need to pass it an empty array

– Shubham Khatri
Nov 23 '18 at 7:12















It's a custom component, i've updated original post, and I've tried the empty array too

– invrt
Nov 23 '18 at 7:19





It's a custom component, i've updated original post, and I've tried the empty array too

– invrt
Nov 23 '18 at 7:19




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53441714%2fre-render-react-component-back-to-original-state%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()