47338

React - how to add new element in array type state?

Question:

I have refereed <a href="https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs" rel="nofollow">this</a> , <a href="https://stackoverflow.com/questions/41052598/reactjs-array-push-function-not-working-in-setstate" rel="nofollow">this</a> and <a href="https://stackoverflow.com/questions/26505064/react-js-what-is-the-best-way-to-add-a-value-to-an-array-in-state" rel="nofollow">this</a> link to find solution but none of them work for me.

I have decleared state with array type and other state with null.

this.state = { from: '', to: '',journeyDate: '',searchDetails: [] }

As user fill up search form with source city , destination city and journey date I set these state like below .

let from = this.state.from; let to = this.state.to; let journeyDate = moment(this.state.journeyDate).format('YYYY-MM-DD');

final step to push these all variables into searchDetails array state. for that I have tried below options but none of them worked.

<blockquote>

OPTION 1

</blockquote> this.setState({ searchDetails: [...this.state.searchDetails, from] }); <blockquote>

OPTION 2

</blockquote> this.setState(prevState => ({ searchDetails: [...prevState.searchDetails, from] })) <blockquote>

OPTION 3

</blockquote> let newState = this.state.searchDetails.slice(); newState.push(from); this.setState({ searchDetails: newState }); console.log('final state is : ' + this.state.searchDetails);

every time console log remains empty.

any advice ?

Answer1:

Try :

this.setState({ searchDetails: newState // use any of your 3 methods to set state },() => { console.log('final state is : ' + this.state.searchDetails); }); <blockquote>

setState() does not always immediately update the component. It may batch or defer the update until later.

This makes reading this.state right after calling setState() a potential pitfall.

Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

</blockquote>

For More Detail, Please read : <a href="https://reactjs.org/docs/react-component.html#setstate" rel="nofollow">https://reactjs.org/docs/react-component.html#setstate</a>

Answer2:

Actually setState is an asynchronous method. That means right after writing setState, you cannot expect the state to be changed immediately. So console.log right after setState may show you last state instead of new state. If you want to log the updated state then use the callback of setState which is called when state is updated like this

this.setState({ searchDetails: [...this.state.searchDetails, from] }, () => { console.log(this.state.searchDetails) });

Recommend

  • Using JQuery Datepicker To Only Show Months
  • How to use java.time.LocalDate on a Play Framework JSON Rest?
  • Year, Month, and Day parameters describe an un-representable DateTime in Persian calender
  • jQuery - how to validate a date of birth using jQuery Validation plugin?
  • jQuery random blockquote
  • A simple datepicker in VueJS
  • How to make Plotly chart with year mapped to line color and months on x-axis
  • How to parsing NSDate to RFC 822 always use in English?
  • iOS Date formatting
  • Cannot convert a char value to money. The char value has incorrect syntax
  • Is there a chance to get -splash: work for SWT applications that require -XstartOnFirstThread?
  • stop execution in Custom validator if it false
  • include dlls in visual studio c++ 2008
  • Is there any way to call saveCurrentTurnWithMatchData without sending a push notification?
  • Angular Bootstrap Carousel Slide Transition not working correctly
  • Get localized short date pattern as String?
  • R Split data.frame using a column that represents and on/off switch
  • Debugging VB6 Code From Visual Studio 2010
  • Silverlight DependencyProperty.SetCurrentValue Equivalent
  • Diff between two dataframes in pandas
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Parse a date string in a specific locale (not timezone!)
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • how to adjust image in a panel in Java swing?
  • Possible to stop flickering java tooltip in heavyweight mode?
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • How to extract text from Word files using C#?
  • Font Awesome Showing Box instead of Icons
  • Properly structure and highlight a GtkPopoverMenu using PyGObject
  • How to set the response of a form post action to a iframe source?
  • JTable with a ScrollPane misbehaving
  • Change div Background jquery
  • Qt: Run a script BEFORE make
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Is it possible to post an object from jquery to bottle.py?
  • Does armcc optimizes non-volatile variables with -O0?
  • reshape alternating columns in less time and using less memory
  • Conditional In-Line CSS for IE and Others?
  • Python/Django TangoWithDjango Models and Databases
  • How to push additional view controllers onto NavigationController but keep the TabBar?