Correct Way to Push into State Array

Pushing To React State Array

// Create a new array based on current state:
let floors = [...this.state.floors];

// Add item to it
floors.push({ value: floorName });

// Set state
this.setState({ floors });

Push method in React Hooks (useState)?

When you use useState, you can get an update method for the state item:

const [theArray, setTheArray] = useState(initialArray);

then, when you want to add a new element, you use that function and pass in the new array or a function that will create the new array. Normally the latter, since state updates are asynchronous and sometimes batched:

setTheArray(oldArray => [...oldArray, newElement]);

Sometimes you can get away without using that callback form, if you only update the array in handlers for certain specific user events like click (but not like mousemove):

setTheArray([...theArray, newElement]);

The events for which React ensures that rendering is flushed are the "discrete events" listed here.

Live Example (passing a callback into setTheArray):

const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}

ReactDOM.render(
<Example />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

how to set state array using react hooks

To insert new element at the end of the list

const addMessage = (newMessage) => setMessages(state => [...state, newMessage])

To insert new element at the begining of the list

const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])

Trying to add to React State Array using spread or push, Error: TypeError: array is not iterable

Well it is because the handleChange is not bound to the Step3 class.
So, when CustomCheckBox invokes the handleChange, the context of this would be referring to CustomCheckBox and not Step3. So, this.missingList is correctly undefined. It's simply the scope of this.

Check this minimal reproducer of your use case. Commenting the bind line will result in the error you have posted.
https://codesandbox.io/embed/upbeat-smoke-q0iei?fontsize=14&hidenavigation=1&theme=dark

Further reading: https://reactjs.org/docs/handling-events.html

How to push array of objects into state using hooks

if res.data.data is an array

then set to setResponses like this

setResponses(res.data.data)

or

setResponses([...responses, ...res.data.data])

Can you use array.push in useEffect? React Hooks

Yes, you can use push in useEffect but not on the state. React state can not be changed directly. As being a state you can not directly push or edit data of the state transactionDataArray. But with the help of setTransactionDataArray function you can change/set the state value. so for you to add new value to it's older state you have to destructure the old state and add the new value like below

setTransactionDataArray([...transactionDataArray, transactionData])

or you can do it like below by creating new variable assigning state's value and than push the new value to the variable and last set the state

const data = transactionDataArray;
data.push(transactionData);
setTransactionDataArray(data);

for more about react state read here



Related Topics



Leave a reply



Submit