Мой почтовый запрос к моему rails-api не дает достаточно времени для генерации моего вторичного идентификатора.Когда я использую setState
в родительском контейнере в функции axios.post
(функция addNewLoad
), мой delivery_id
(пользовательский дополнительный идентификатор в базе данных) возвращает null
в this.state.apiData
.
Если я обновляю страницу, delivery_id
заполняется ПРАВИЛЬНЫМИ данными, но мне нужно, чтобы данные были правильными, когда я возвращаю response
и использую setState
в запросе POST
.
Я понятия не имею, что происходит!
Родительский контейнер, в котором я использую axios для GET
и POST
:
export default class PickupDeliveries extends Component {
state = {
apiData: [],
}
componentDidMount(){
// gets all the pickup/deliveries
axios.get('http://localhost:3001/api/v1/pickup_deliveries')
.then((response) => {
console.log(response);
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
addNewLoad = (pickup_date, pickup_location, rate, delivery_date, delivery_location, local, loaded_miles, deadhead_miles, delivery_id, pickup_zip, delivery_zip) => {
let config = {
headers: {
'Content-Type': 'application/json; charset=utf-8', "Accepts": "application/json",
}
}
const instance = axios.create({baseURL: 'http://localhost:3001'})
instance.post('/api/v1/pickup_deliveries', {pickup_date, pickup_location, rate, delivery_date, delivery_location, local, loaded_miles, deadhead_miles, delivery_id, pickup_zip, delivery_zip}, config)
.then(response => {
this.setState({apiData: [ ...this.state.apiData, response.data ] })
})
.catch(error => {
console.log(error)
})
}
Это дочерний компонент, который использует this.props.addNewLoad
для отправки данных формы:
handleSubmit = (e) => {
e.preventDefault()
this.props.onNewLoad(
this.state.pickup_date,
this.state.pickup_location,
this.state.rate,
this.state.delivery_date,
this.state.delivery_location,
this.state.local,
this.state.loaded_miles,
this.state.deadhead_miles,
this.state.delivery_id,
this.state.pickup_zip,
this.state.delivery_zip
)
this.setState({
pickup_date: new Date(),
pickup_zip: '',
pickup_location: '',
rate: '',
delivery_zip: '',
delivery_date: new Date(),
delivery_location: '',
loaded_miles: '',
deadhead_miles: '',
local: false,
delivery_zip: '',
association_zip: '',
delivery_id: ''
})
}
Вот моя база данных:
ActiveRecord::Schema.define(version: 2019_05_17_163434) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "pickup_deliveries", force: :cascade do |t|
t.date "pickup_date"
t.text "pickup_location"
t.money "rate", scale: 2
t.date "delivery_date"
t.text "delivery_location"
t.boolean "local"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "loaded_miles", default: 0
t.integer "deadhead_miles", default: 0
t.integer "delivery_id", default: -> { "nextval('delivery_id_seq'::regclass)" }
t.text "pickup_zip"
t.text "delivery_zip"
end
end
Вот как я устанавливаю функцию приращения для своего вторичного идентификатора:
class AddJobIdSequenceToScores < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
ALTER SEQUENCE delivery_id_seq OWNED BY pickup_deliveries.delivery_id;
ALTER TABLE pickup_deliveries ALTER COLUMN delivery_id SET DEFAULT nextval('delivery_id_seq');
SQL
end
def down
execute <<-SQL
ALTER SEQUENCE delivery_id_seq OWNED BY NONE;
ALTER TABLE pickup_deliveries ALTER COLUMN delivery_id SET NOT NULL;
SQL
end
end
Я в растерянности, и любая помощь очень ценится.
РЕДАКТИРОВАТЬ:
Вот мой контроллер:
module Api::V1
class PickupDeliveriesController < ApplicationController
before_action :set_pickup_delivery, only: [:show, :update, :destroy]
# GET /pickup_deliveries
def index
@pickup_deliveries = PickupDelivery.all
render json: @pickup_deliveries
end
# GET /pickup_deliveries/1
def show
render json: @pickup_delivery
end
# POST /pickup_deliveries
def create
@pickup_delivery = PickupDelivery.new(pickup_delivery_params)
if @pickup_delivery.save
render json: @pickup_delivery, status: :created, location: @pickup_delivery_url
else
render json: @pickup_delivery.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /pickup_deliveries/1
def update
if @pickup_delivery.update(pickup_delivery_params)
render json: @pickup_delivery
else
render json: @pickup_delivery.errors, status: :unprocessable_entity
end
end
# DELETE /pickup_deliveries/1
def destroy
@pickup_delivery.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pickup_delivery
@pickup_delivery = PickupDelivery.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def pickup_delivery_params
params.require(:pickup_delivery).permit(:id, :pickup_date, :pickup_location, :rate, :delivery_date, :delivery_location, :local, :loaded_miles, :deadhead_miles, :delivery_id, :pickup_zip, :delivery_zip)
end
end
end