#javascript #html #reactjs
#javascript #HTML #reactjs
Вопрос:
У меня есть две таблицы, «Член» и «Адрес», которые связаны. В моей форме есть поля для обеих таблиц, и я хочу, чтобы мое приложение возвращало идентификатор участника и использовало его во внешнем ключе адреса, однако, когда я пытаюсь изменить значение id_member с помощью ответа функции post, оно не меняется и остается без значения.
import React, { useState, useEffect } from 'react';
import { Link, useHistory } from 'react-router-dom';
import { FiArrowLeft } from 'react-icons/fi';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Form, Col } from 'react-bootstrap';
import api from '../../services/api';
import './styles.css';
export default function NewMember() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [situation, setSituation] = useState('');
const [birth, setBirth] = useState('');
const [rg, setRg] = useState('');
const [street, setStreet] = useState('');
const [number, setNumber] = useState('');
const [neighborhood, setNeighborhood] = useState('');
const [city, setCity] = useState('');
const [uf, setUf] = useState('');
const [zip, setZip] = useState('');
const [id_member, setId_member] = useState(0);
const history = useHistory();
const userId = localStorage.getItem('userId');
async function handleNewMember(e) {
e.preventDefault();
const dataMember = {
name,
email,
situation,
birth,
rg,
};
const dataAddress = {
street,
number,
neighborhood,
city,
uf,
zip,
id_member,
};
try {
const response = await api.post('members', dataMember, {
headers: {
Authorization: userId,
}
})
setId_member(response.data.id);
await api.post('/address', dataAddress);
history.push('/profile');
} catch (err) {
alert('Erro ao cadastrar integrante, tente novamente.')
}
}
return (
<div className="new-member-container">
<div className="content">
<Form onSubmit={handleNewMember}>
<Form.Row className="space">
<Col xs={7}>
<Form.Label>Nome</Form.Label>
<Form.Control
type="text"
placeholder="João Alves da Silva"
value={name}
onChange={e => setName(e.target.value)}
/>
</Col>
<Col>
<Form.Label>E-mail</Form.Label>
<Form.Control
type="email"
placeholder="e-mail@gmail.com"
value={email}
onChange={e => setEmail(e.target.value)}
/>
</Col>
</Form.Row>
<Form.Row className="space">
<Col xs={6}>
<Form.Label>Nascimento</Form.Label>
<Form.Control
type="date"
placeholder="24/01/2000"
value={birth}
onChange={e => setBirth(e.target.value)}
/>
</Col>
<Col>
<Form.Label>RG</Form.Label>
<Form.Control
placeholder="50.149.996-9"
value={rg}
onChange={e => setRg(e.target.value)}
/>
</Col>
</Form.Row >
<Form.Row className="space">
<Col xs={6}>
<Form.Label>Rua</Form.Label>
<Form.Control
placeholder="Rua Loefgren"
value={street}
onChange={e => setStreet(e.target.value)}
/>
</Col>
<Col>
<Form.Label>Número</Form.Label>
<Form.Control
placeholder="2109"
value={number}
onChange={e => setNumber(e.target.value)}
/>
</Col>
<Col xs={4}>
<Form.Label>Bairro</Form.Label>
<Form.Control
placeholder="Vila Clementino"
value={neighborhood}
onChange={e => setNeighborhood(e.target.value)}
/>
</Col>
</Form.Row >
<Form.Row className="space">
<Col xs={4}>
<Form.Label>City</Form.Label>
<Form.Control
placeholder="São Paulo"
value={city}
onChange={e => setCity(e.target.value)}
/>
</Col>
<Col xs={2}>
<Form.Label>UF</Form.Label>
<Form.Control
placeholder="SP"
value={uf}
onChange={e => setUf(e.target.value)}
/>
</Col>
<Col xs={2}>
<Form.Label>CEP</Form.Label>
<Form.Control
placeholder="04040-030"
value={zip}
onChange={e => setZip(e.target.value)}
/>
</Col>
<Col>
<Form.Label>Situação</Form.Label>
<Form.Control
value={situation}
placeholder="Ativo"
onChange={e => setSituation(e.target.value)}>
</Form.Control>
</Col>
</Form.Row>
<button className="button" type="submit">
Cadastrar
</button>
<Link className="back-link" to="/profile">
<FiArrowLeft size={16} color="#01A8E5" />
Voltar para Home
</Link>
</Form>
</div>
</div>
);
}
Мой контроллер:
const connection = require('../database/connection');
module.exports = {
async index(request, response) {
const { page = 1 } = request.query;
const [count] = await connection('member').count();
const members = await connection('member')
.join('address', 'id_member', '=', 'member.id')
.limit(30)
.offset((page - 1) * 30)
.select([
'member.*',
'address.street',
'address.number',
'address.neighborhood',
'address.city',
'address.uf',
'address.zip']);
response.header('X-Total-Count', count['count(*)']);
return response.json(members);
},
async create(request, response) {
const { name, email, situation, birth, rg } = request.body;
const [id] = await connection('member').insert({
name,
email,
situation,
birth,
rg,
});
return response.json({ id });
},
async delete(request, response) {
const { id } = request.params;
const members = await connection('member')
.where('id', id)
.select('id')
.first();
if (!members) {
return response.status(404).json({ error: 'Operation Not Found.' });
}
else {
await connection('member').where('id', id).delete();
return response.status(204).send();
}
}
};
Комментарии:
1. Можете ли вы опубликовать код для <Form.Control/>?
Ответ №1:
async function handleNewMember(e) {
e.preventDefault();
const dataMember = {
name,
email,
situation,
birth,
rg,
};
const dataAddress = {
street,
number,
neighborhood,
city,
uf,
zip
};
try {
const response = await api.post('members', dataMember, {
headers: {
Authorization: userId,
}
})
const id_member = response.data.id
setId_member(id_member);
// `setId_member` or setXxx is async. so use the `id_member` directly. or you will always get it's previous value
dataAddress.id_member = id_member
await api.post('/address', dataAddress);
history.push('/profile');
} catch (err) {
alert('Erro ao cadastrar integrante, tente novamente.')
}
}
Комментарии:
1. все в порядке. хорошего дня 😉