Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
How to change a useState's object value in react?

After getting member data, member state will be like this.

{
  _id: '61d34027ca50827501279eb0',
  index: 1,
  email: 'bcr90348@zwoho.com',
  name: '1',
  active: true
}

How to change the values of the above object by changing the text box values?

Ex: Changing the name. Changing email.

import React, { useEffect, useState } from 'react'
import {
  CButton,
  CCard,
  CCardBody,
  CCardHeader,
  CCol,
  CForm,
  CFormInput,
  CFormLabel,
  CRow,
} from '@coreui/react'
import PropTypes from 'prop-types'

const Edit = (props) => {
  const id = props.match.params.id
  const [member, setMember] = useState({})

  const handleLoadMember = async () => {
    try {
      const _data = await fetch(`http://localhost:4000/api/v1/member/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + localStorage.getItem('token'),
        },
      })

      if (_data.status === 200) {
        const data = await _data.json()
        setMember(data.member)
      } else if (_data.status === 404) {
      } else {
        throw new Error()
      }
    } catch (err) {
      console.error(err)
    }
  }

  useEffect(() => {
    handleLoadMember()
  }, [])

  return (
    <CRow>
      <CCol xs={12}>
        <CCard className="mb-4 w-75">
          <CCardHeader>
            <strong>Add New Member</strong>
          </CCardHeader>
          <CCardBody>
            <p className="text-medium-emphasis small">
              Click on save button after editing member details.
            </p>
            <CForm>
              <div className="d-inline-flex w-100">
                <div className="mb-3 me-1 w-50">
                  <CFormLabel>Email:</CFormLabel>
                  <CFormInput
                    type="email"
                    placeholder="name@example.com"
                    value={member.email}
                    onChange={(e) => console.log(e.target.value)}
                  />
                </div>

                <div className="mb-3 w-50">
                  <CFormLabel>Name:</CFormLabel>
                  <CFormInput type="text" placeholder="Perera's Home" value={member.name} />
                </div>
              </div>
              <div className="mb-3">
                <CButton color="primary">Submit</CButton>
              </div>
            </CForm>
          </CCardBody>
        </CCard>
      </CCol>
    </CRow>
  )
}

Edit.propTypes = {
  match: PropTypes.any,
}

export default Edit
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Assuming that member already has a value (like you described in your question), you can alter one or multiple properties of it by doing something like this with the spread operator:

setMember(member => ({...member, name: "My New Name", email: "NewEmail"}))

See the Hooks API and useState documentation for more information.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can define an onChangeHandler like below. And add define name prop to each field.

  const onChangeHandler = (e) => {
    const { name, value } = e.target;
    setMember((prevState) => ({ ...prevState, [name]: value }));
  };
<CFormInput
    type="email"
    placeholder="name@example.com"
    name="email"
    onChange={onChangeHandler}
    value={member.email}
 />
<CFormInput
     type="text"
     placeholder="Perera's Home"
     name="name"
     onChange={onChangeHandler}
     value={member.name}
 />

Code sandbox

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda