How to update arrays in react state

How to update arrays in react state

Introduction

Although JavaScript arrays are immutable by default, react state requires that you consider arrays as mutable, which is difficult for most react newbies to comprehend. We will talk about how to update an array in react state without changing the initial array in this article.

Prerequisites

To properly understand this tutorial, you'll need the following:

  • Have a code editor installed on your PC

  • Have a working knowledge of JavaScript and React

  • Your machine must have Node installed. Downloads are available at nodejs.org

  • The npm package manager, which is included with the Node installation. If you choose, you can also use yarn. Run npm install -global yarn in your terminal to install yarn, and then yarn -version to see if it was successful.

Setting up working environment

To create a react app, open your code editor's terminal and navigate to the directory where you want to save it:

cd directory-name

Run the following command to create a react app locally on your computer after selecting the directory in which you wish to save your project:

npx create-react-app project-name

Or

yarn create-react-app project-name

Once installed, go to your project directory and start the server.

cd project-name
npm start

First, make a simple form with fields for the user's first and last names and a button.

import React from "react";
const App = () => {
    return (
        <div>
            <input 
                type="text" 
                placeholder="First Name" 
            />
            <input 
                type="text" 
                placeholder="Last Name" 
            />
            <button>Submit</button>
        </div>
    )
}

Second, make a state that will store the input field values.

import React, {useState} from "react"

const App = () => {
    const [name, setName] = useState({firstName: "", lastName: ""})
    return (
        <div>
            <input 
                type="text" 
                placeholder="First Name" 
            />
            <input 
                type="text" 
                placeholder="Last Name" 
            />
            <button>Submit</button>
        </div>
    )
}

Now let's update the code.

import React, {useState} from "react";
const App = () => {
    const [name, setName] = useState({firstName: "", lastName: ""})
    const [users, setUsers] = useState([]);

    const handleChange = (event)=> {
        setName(prevName => {
            return {
                ...prevName,
                [event.target.name]: event.target.value
            }
        })
    }
    return (
        <div>
            <input 
                type="text" 
                placeholder="First Name" 
                name="firstName" 
                value={name.firstName} 
                onChange={handleChange} 
            />
            <input 
                type="text" 
                placeholder="Last Name" 
                name="lastName" 
                value={name.lastName} 
                onChange={handleChange} 
            />
            <button onClick={handleClick}>Submit</button>
        </div>
    )
}

You can see that we updated our code; now let's examine what has changed.

  1. The input tag's "name" property refers to the user information, in this case, "firstName & lastName."

  2. The input tag's "value" attribute refers to the firstName and lastName values, which are initially set to an empty string. As we enter text into the input box, this will update.

  3. Our handleChange function, which is declared in the App component, will be called by the input tag's "onChange" property.

  4. Whenever the button is clicked, the "onClick" property in the button will trigger the handleClick function to be called. In the next block of code, we will define the handleClick function.

  5. All user information will be stored in the new state, users.

Adding to an array

The push() method is the first thing that most people think of when adding to an array. Because the push() method modifies the initial/original array, which is not what you want to do in this situation, this won't work when it comes to react state.

In react state, you need to use the concat() method or the spread operator(...) to add to an array.

The concat() method is used when combining two or more arrays. It returns a new array rather than altering the original arrays. For a better understanding, learn more about the concat() method

The spread operator(...) allows us to easily copy all or a portion of an existing array or object into another array or object. Also available at w3schools is more information on the spread operator.

Using concat() method

import React, {useState} from "react";
const App = () => {
    const [name, setName] = useState({firstName: "", lastName: ""})
    const [users, setUsers] = useState([]);

    const handleClick = ()=> {
        setUsers(prevUsers => {
            return prevUsers.concat(name)
        })
    }
}

Using spread operator:

import React, {useState} from "react";

const App = () => {
    const [name, setName] = useState({firstName: "", lastName: ""})
    const [users, setUsers] = useState([]);

    const handleClick = ()=> {
        setUsers(prevUsers => {
            return [...prevUsers, name]
        })
    }
}

This is how the complete code will look;

import React, {useState} from "react";
const App = () => {
    const [name, setName] = useState({firstName: "", lastName: ""})
    const [users, setUsers] = useState([]);
    const handleChange = (event)=> {
        setName(prevName => {
            return {
                ...prevName,
                [event.target.name]: event.target.value
            }
        })
    }
    const handleClick = ()=> {
        setUsers(prevUsers => {
            return [...prevUsers, name]
        })
    }
    return(
        <div>
            <input 
                type="text" 
                placeholder="First Name" 
                name="firstName" 
                value={name.firstName} 
                onChange={handleChange} 
            />
            <input 
                type="text" 
                placeholder="Last Name" 
                name="lastName" 
                value={name.lastName} 
                onChange={handleChange} 
            />
            <button onClick={handleClick}>Submit</button>
        </div>
    )
}

We can now map through the array and do some manipulations.

Removing items from an array

The filter() method can be used to exclude certain items from an array, which is the simplest way to do so. Use the filter() method to eliminate elements from an array based on specific conditions. The new array of objects that pass a certain test is returned by the filter() method.

Example:

import React, {useState} from "react";
const App = () => {
    const [users, setUsers] = useState([
        { id: 0, firstName: 'John', lastName: 'Doe' },
        { id: 1, firstName: 'James', lastName: 'Billy' },
        { id: 2, firstName: 'Bob', lastName: 'Sky' }
    ])
    const newUsers = users.filter(item => {
        return item.id !== 0;
    })
    console.log(newUsers);
    //Output: [
            {id: 1, firstName: 'James', lastName: 'Billy'},
            {id: 2, firstName: 'Bob', lastName: 'Sky'}
        ]
}

The above code returns a new array of items with ids other than 0.

The firstName or lastName keys can also be used to remove an item.

Example:

import React, {useState} from "react";
const App = () => {
    const [users, setUsers] = useState([
        { id: 0, firstName: 'John', lastName: 'Doe' },
        { id: 1, firstName: 'James', lastName: 'Billy' },
        { id: 2, firstName: 'Bob', lastName: 'Sky' }
    ])
    const newUsers = users.filter(item => {
        return item.firstName !== ‘John’;
    })
    console.log(newUsers);
    //Output: [
            {id: 1, firstName: 'James', lastName: 'Billy'},
            {id: 2, firstName: 'Bob', lastName: 'Sky'}
        ]
}

The above code creates a new array of objects having firstNames other than "John."

Conclusion

We've just talked about adding and removing items from an array in react state to update it. We also discussed the benefits of using the spread operator and concat() method over other array methods.