Home > Software design >  An object from arrays of objects - React - useState
An object from arrays of objects - React - useState

Time:06-29

help please I want to add value to state without overwriting. Currently, when adding a value, the array is overwritten. I want to use useState and I want to use the value from the form.

import {useState} from 'react';

const initialState = {
    people: [
        {email: 'Jan'},
        {email: 'Izabela'},
        {email: 'Michael'}
    ] }

const StateModification = () => {

    const [names,setNames] = useState(initialState)

    const handleSubmit = (e) => {
        e.preventDefault(); 
    }

    const handleChange2 = (e) => {
        setNames({
            ...names,
            people: [{[e.target.name]: e.target.value}]
        })
    }

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <label>E-mail</label>
                <input 
                    id='email' 
                    type='text' 
                    name='email'
                    value={names.email}
                    onChange={handleChange2}    
                />
                
                <button type='submit'>Add</button>
            </form>
        </div>`enter code here`
    ) }

export default StateModification;

CodePudding user response:

I think you need to add an email in your data and after click on add button that email will store in people variable with your previous data so i have update your code and it should work for you.

import {useState} from 'react';

const initialState = {
    people: [
        {email: 'Jan'},
        {email: 'Izabela'},
        {email: 'Michael'}
    ] }

const StateModification = () => {

    const [names,setNames] = useState(initialState)
    const [email,setEmail] = useState("")

    const handleSubmit = (e) => {
      e.preventDefault();
        setNames({
          people: [...names.people, { email }]
      })
    }

    const handleChange2 = (e) => {
      e.preventDefault();
      setEmail(e.target.value)
    }

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <label>E-mail</label>
                <input 
                    id='email' 
                    type='text' 
                    name='email'
                    value={email}
                    onChange={handleChange2}    
                />
                
                <button type='submit'>Add</button>
            </form>
        </div>
    ) }

export default StateModification;

CodePudding user response:

Looks better. But now it gets added to the state of each letter :-/

{people: Array(8)}
people: Array(8)
0: {email: 'Jan'}
1: {email: 'Izabela'}
2: {email: 'Michael'}
3: {email: 'N'}
4: {email: 'No'}
5: {email: 'Now'}
6: {email: 'Nowa'}
7: {email: 'Nowak'}
  • Related