score:210
Array push returns length
this.state.myArray.push('new value')
returns the length of the extended array, instead of the array itself.Array.prototype.push().
I guess you expect the returned value to be the array.
Immutability
It seems it's rather the behaviour of React:
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.React.Component.
I guess, you would do it like this (not familiar with React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
score:-1
I guess this is a little bit late for an answer but for those new to react
You can use this tiny package called immer
see this example: https://immerjs.github.io/immer/produce
score:0
you are breaking React principles, you should clone the old state then merge it with the new data, you shouldn't manipulate your state directly, your code should go like this
fetch('http://localhost:8080').then(response => response.json()).then(json ={this.setState({mystate[...this.state.mystate, json]}) })
score:1
In the following way we can check and update the objects
this.setState(prevState => ({
Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));
score:1
setState([...prevState, {
label: newState.name,
value: newState.id
}]);
Was working with the dropdowns and wanted to implement this scenario there, i found this simple solution for dropdown with multiple values.
score:2
React-Native
if u also want ur UI (ie. ur flatList) to be up to date, use PrevState: in the example below if user clicks on the button , it is going to add a new object to the list( both in the model and UI)
data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}.
score:3
This Code work for me :
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
score:13
Using react hooks, you can do following way
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
score:17
You can use .concat
method to create copy of your array with new data:
this.setState({ myArray: this.state.myArray.concat('new value') })
But beware of special behaviour of .concat
method when passing arrays - [1, 2].concat(['foo', 3], 'bar')
will result in [1, 2, 'foo', 3, 'bar']
.
score:20
Here you can not push the object to a state array like this. You can push like your way in normal array. Here you have to set the state,
this.setState({
myArray: [...this.state.myArray, 'new value']
})
score:25
You should not be operating the state at all. At least, not directly. If you want to update your array, you'll want to do something like this.
var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);
Working on the state object directly is not desirable. You can also take a look at React's immutability helpers.
score:101
Functional Components & React Hooks
const [array,setArray] = useState([]);
Push value at the end:
setArray(oldArray => [...oldArray,newValue] );
Push value at the start:
setArray(oldArray => [newValue,...oldArray] );
score:156
Never recommended to mutate the state directly.
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
Push string to end of the array
this.setState(prevState => ({
myArray: [...prevState.myArray, "new value"]
}))
Push string to beginning of the array
this.setState(prevState => ({
myArray: ["new value", ...prevState.myArray]
}))
Push object to end of the array
this.setState(prevState => ({
myArray: [...prevState.myArray, {"name": "object"}]
}))
Push object to beginning of the array
this.setState(prevState => ({
myArray: [ {"name": "object"}, ...prevState.myArray]
}))
score:279
Using es6 it can be done like this:
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
Source: stackoverflow.com
Related Query
- Correct way to push into state array
- ReactJS - push json into state array
- Correct way to add items to an array stored in React state with useState hook?
- push empty array into react's state
- Push method converts an array into a number in the component state
- How to push to an object to an array which is a state object, react way with Typescript
- React Reducer Correct Way To Return An Array With State
- what is the correct way to add data array to the array state as well
- How to push textfield and dropdown values into state array
- React Push One State Array into Another
- Correct way to handle value change of an input element mapped from array held in state
- What is the correct way to push jsx with embedded js variables on to an array
- Correct way to push an item to array in javascript
- How do I take an array of objects from state and push a specific value of the objects into a new array
- How to push array of objects into state using hooks
- push state object into state array in reactJS application
- Push items into empty State array of objects
- Correct way to update a state array in a Flux Store
- REACT, Axios, cloudinary push mutliple secure_urls Into State Array In Reactjs
- What is the best way to add a value to an array in state
- Correct way to type nullable state when using React's useState hook
- How can I insert into React's state array with setState?
- Correct way of Creating multiple stores with mobx and injecting it into to a Component - ReactJs
- Correct way (if possible) to store JSX code into a Javascript variable
- Correct way to throttle HTTP calls based on state in redux and react
- How to push into an array of object using the spread operator to a specific element
- Push checkbox value to array on state onChange
- (React) Correct way to typecheck array of objects that may be empty?
- Correct way to remove key from react state
- In React, what is the right way to update nested array state items
More Query from same tag
- React - checkbox values are undefined despite having a default value
- Unhandled Rejection (SyntaxError): Unexpected end of input
- Pupeteer click on bootstrap card
- Uncaught Error: Ziggy error: 'blog' parameter is required for route 'blogs.show'
- useEffect not running at all when navigating to page with React Router
- Stale state in React causing duplicate API requests
- useQuery to conditionally render data
- Initializing useState by modifying (mapping through) values of redux state
- Image is not visible (source is not recognized)
- Why are for loops not allowed in React - JSX?
- How can I get a specific key value from another schema, By comparing if they have same key value?
- How to pass data from parent to children with react hooks
- How can I treat an array of values to be a tuple that is inferred based on what's passed to it
- Objects are not valid as a React child using react router v4
- Dynamically loading JSON files with fetch after component mounts in React?
- Cannot create custom style with React and Bootstrap
- Problems with ReactRouter 4 when using externals for React,ReactDOM and ReactRouter
- How to redirect user to another page on redux saga without reloading the page
- Need to edit Moment in Antd Datepicker to display full name of month
- chat app using mern stack and socket.io getting slow after sending more than 20 messages
- React's useSelector with array of objects
- How to pass function as prop in react routerv5 with the Link tag
- Changing a component in reactjs upon clicking a button
- Why do I get 'implied eval. Consider passing a function instead of a string' when passing a simple string to state?
- Using svg-url-loader with Create React App
- Unable to display array of only one object using reactjs
- React-Leaflet: Placing map control components outside of map?
- Cannot read properties of null (reading 'video')
- How to fix error "argument of type (open: any) => boolean is not assignable to parameter of type boolean" using react and typescript?
- Dispatch is not a function react