- Forums
 - react
 - React Push Or Append To Usestate Array - Append New Array To Existing Array
 
This Page Contains information about React Push Or Append To Usestate Array - Append New Array To Existing Array By cathy in category react with 0 Replies. [5186], Last Updated: Mon Jun 24, 2024 
 
 cathy
 Mon Aug 21, 2023 
 0 Comments
 726 Visits
To add, append or push to a useState array in React you can do this for examle:
Example A - push one item to an array
const [score, setScore] = useState({correct:[],wrong:[]});
 
// push correct
 setScore({...score, correct: [...score.correct, QuizQuestionIds[currentQ]] });
 
 
Example 1 - push one item to an array
setMyArray(myArray => [...myArray, 'Johnny']);
 
Example 2. Push an array into array from an API results. This will keep exisiting keys and just add the additional keys from the API returned array.
setTasks(Tasks => [...Tasks, api.data[i]]);
 
examle 3: Specify the index
setTasks({...Tasks, [index]: res.data });
 
hope that helps.
Resource: https://bobbyhadz.com/blog/react-push-to-state-array