REACT Condition for NULL value in Input

Asked

Viewed 51 times

0

I have a question on React when doing a data update for a student where I use the useEffect() to retrieve the student’s data and take them to the form by placeholder={} and then I have a onChange that takes the data from input and play for data update function.

I want this function to update only the data entered in input and the others remain the same as the placeholder={}, but I’ve tried it in many ways and I haven’t come to a conclusion.

Front

export default function EditMyDataStudent() {
    const [students, setStudents] = useState([]);
    const [nameStudent, setNameStudent] = useState('');
    const [studentId, setStudentId] = useState('');
    const [emailStudent, setEmailStudent] = useState('');
    const [whatsappStudent, setWhatsappStudent] = useState('');
    const [studentDateBirth, setStudentDateBirth] = useState('');
    const [nameDadStudent, setNameDadStudent] = useState('');
    const [nameMotherStudent, setNameMotherStudent] = useState('');
    const [numberResponsible, setNumberResponsible] = useState('');
    const [matriculation, setMatriculation] = useState('');
    const [studentDateRegister, setStudentDateRegister] = useState('');

    const history = useHistory();

    const studentCpf = localStorage.getItem('studentCpf');
    const nameS = localStorage.getItem('nameStudent');


    useEffect(() => {
        api.get('students', {
            headers: {
                Authorization: studentCpf,
            }
        }).then(response => {
            setStudents(response.data);
        })
    }, [studentCpf]);

    function handleLogout() {
        localStorage.clear();

        history.push('/sessions');
    }

    function handleCancel() {
        localStorage.setItem('studentCpf', studentCpf);
        localStorage.setItem('nameStudent', nameS);

        history.go(0);
    }

    async function handleUpdate(e) {
        
        const data = {
            nameStudent,
            emailStudent,
            whatsappStudent,
            studentDateBirth,
            nameDadStudent,
            nameMotherStudent,
            numberResponsible,
            matriculation,
            studentDateRegister
        };

        
        try {
            await api.put(`students/${studentCpf}`, data);


            history.push('/mydatastudent');
        } catch (err) {
            alert('Erro no cadastro, tente novamente.');
        }
    }

    return (
        <div className="profile-container">
            <header>
                <img src={schoolIso} alt="student Isotipo" />
                <span>Bem vindo, {nameS}</span>

                <Link className="button" to="/">Agenda</Link>
                <button onClick={handleLogout} type="button">
                    <FiPower size={18} color="#E02041" />
                </button>
            </header>

            <Tabs className="menu" value={false}>
                <Tab className="tab" label="Meus Dados" />
                <Tab className="tab" label="Grade de Aulas" />
                <Tab className="tab" label="Grade de Professores" />
                <Tab className="tab" label="Trabalhos" />
                <Tab className="tab" label="Avaliações" />
            </Tabs>

            <div className="title">
                <h1>Meus Dados</h1>
            </div>

            <ul>
                {students.map(student => (
                    <li key={student.studentCpf} >

                        <strong>Nome:</strong>
                        <input
                            placeholder={student.nameStudent}
                            value={nameStudent}
                            onChange={e => setNameStudent(e.target.value)}
                        />

                        <strong >CPF:</strong>
                        <input
                            placeholder={student.studentCpf}
                            value={studentId}
                            onChange={e => setStudentId(e.target.value)}
                        />


                        <strong>Email:</strong>
                        <input
                            placeholder={student.emailStudent}
                            value={emailStudent}
                            onChange={e => setEmailStudent(e.target.value)}
                        />


                        <strong>Whatsapp:</strong>
                        <input
                            placeholder={student.whatsappStudent}
                            value={whatsappStudent}
                            onChange={e => setWhatsappStudent(e.target.value)}
                        />

                        <strong>Data Nascimento:</strong>
                        <input
                            placeholder={student.studentDateBirth}
                            value={studentDateBirth}
                            onChange={e => setStudentDateBirth(e.target.value)}
                        />


                        <strong>Nome do Pai:</strong>
                        <input
                            placeholder={student.nameDadStudent}
                            value={nameDadStudent}
                            onChange={e => setNameDadStudent(e.target.value)}
                        />


                        <strong>Nome da Mãe:</strong>
                        <input
                            placeholder={student.nameMotherStudent}
                            value={nameMotherStudent}
                            onChange={e => setNameMotherStudent(e.target.value)}
                        />


                        <strong>Numero do Responsável:</strong>
                        <input
                            placeholder={student.numberResponsible}
                            value={numberResponsible}
                            onChange={e => setNumberResponsible(e.target.value)}
                        />


                        <strong>Matrícula:</strong>
                        <input
                            placeholder={student.matriculation}
                            value={matriculation}
                            onChange={e => setMatriculation(e.target.value)}
                        />


                        <strong>Data de Registro:</strong>
                        <input
                            placeholder={student.studentDateRegister}
                            value={studentDateRegister}
                            onChange={e => setStudentDateRegister(e.target.value)}
                        />


                        <button type="button" style={{ right: 40 }} onClick={e => handleUpdate(student, e)} >
                            <BiCheck size={20} color="#a8a8b3" />
                        </button>
                        <button type="button" style={{ right: 60 }} onClick={handleCancel} >
                            <BiX size={20} color="#a8a8b3" />
                        </button>
                    </li>
                ))}
            </ul>
        </div>
    );
}

Back

async update(request, response) {
    console.log('aq')
    const { studentCpf } = request.params;
    const { nameStudent,
        emailStudent,
        whatsappStudent,
        studentDateBirth,
        nameDadStudent,
        nameMotherStudent,
        numberResponsible,
        matriculation,
        studentDateRegister } = request.body;

    const student = await connection('students')
        .where('studentCpf', studentCpf)
        .update({
            'nameStudent': nameStudent,
            'emailStudent': emailStudent,
            'whatsappStudent': whatsappStudent,
            'studentDateBirth' :studentDateBirth,
            'nameDadStudent' :nameDadStudent,
            'nameMotherStudent': nameMotherStudent,
            'numberResponsible': numberResponsible,
            'matriculation' :matriculation,
            'studentDateRegister' :studentDateRegister
        })
    

    if(student.studentCpf =! studentCpf){
        return response.status(401).json({ error: 'Operation not permitted' })
    }

    return response.status(204).send();
}
  • You get a list of Students correct and load this all on the screen and use another state to record that modification then it is wrong, because it should change the positions of Students, I think that’s what you want to do? (I think) I don’t quite understand why there is this inconsistency in your form.

  • @novic in the placeholder() I search for the existing data. And in useState() I use to save the modifications. That is, a student enters the editingDados area and can see their data already recorded in a placeholder() as well as have the option to update them.

  • if you are changing a correct list?

  • yes! It’s an update page.

  • does not need all variables that you created only by the list you can change

1 answer

0

You are receiving a list of values and by the way you have created a single state variable for everything, this is the problem, when you have a list of values you have to change the position of each item in the list separately, but as?

Minimum example for changing list items:

function App() {  
  const [items, setItems] = React.useState([
    {"id": 1, "name": "item 1", "status": true},
    {"id": 2, "name": "item 2", "status": true},
    {"id": 3, "name": "item 3", "status": false},
  ]); 
  const handleChange = (e, id) => {    
  
    const value = e.target.type === 'checkbox' 
      ? e.target.checked 
      : e.target.value;
    const { name } = e.target;    
      
    setItems(state => [
      ...state.map(item => {
        if (item.id === id) {        
          return { ...item, [name]: value };
        }
        return item;
      })
    ]);
  }
  return (
    <div>
      {items.map((item, indice) => (
        <div key={indice}>
          <div>{item.id}</div>
          <div>
            <input 
              name="name"
              value={item.name} 
              onChange={e => handleChange(e, item.id)}
            />
            <input 
              name="status"
              type="checkbox"
              onChange={e => handleChange(e, item.id)}
              checked={item.status}
            />
          </div>
        </div>
      ))}
      <pre>{JSON.stringify(items, null, '\t')}</pre>
    </div>
  )
}

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

check that by entering the value in the box the same will change the key that represents that set of information, and as you did is not exactly how it should be done, also add two field types to understand that each field can have its peculiarity, but, the difference is with these two elements.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.