Мне надо сделать получение ввода по полям он закидывает данные которые есть и если каких либо не хватает то прости дозаполнить, вот более подробнее об этом:
Сделать выбор от 2 до 4 участков и соответственно столько значений надо в p_ejector дополнять в зависимсости от участков, изначально 2, если неизвестно, p_values всегда 3 элемента, с остальными тоже все фиксировано, пример json для calculate API:
{
"turbine_name": "string",
"valve_drawing": "string",
"valve_id": 0,
"temperature_start": 0,
"t_air": 0,
"count_valves": 0,
"p_ejector": [
0
],
"p_values": [
0
]
}
Так должны выглядеть отправленные данные на API, вот что выдаст в случае успеха
{
"id": 0,
"user_name": "string",
"stock_name": "string",
"turbine_name": "string",
"calc_timestamp": "2024-12-02T22:12:23.306Z",
"input_data": {},
"output_data": {}
}
Потом переходим по схеме такой как когда тыкнули что не требуется перерасчет но уже только с этими значениями
StockInputPage.tsx
import React, { useState, useEffect } from 'react';
import './StockInputPage.css';
type Props = {
stock: any;
onSubmit: (data: any) => void;
initialData?: any; // Добавляем пропс для начальных данных
};
It looks like you're trying to create a dynamic input form in React where users can select between 2 to 4 sections, and based on that selection, the number of input fields for p_ejector adjusts accordingly. You also need to ensure that p_values always has 3 elements, and you want to send this data to an API in a specific JSON format.
From your description and the provided code, here's how you can achieve this:
Ensure Dynamic Rendering of p_ejector Inputs:
Your StockInputPage.tsx component should adjust the number of p_ejector input fields based on the user's selection. The code you have for handling this seems mostly correct. However, there are a few things we can adjust to ensure it works as expected.
Parsing Numeric Inputs Correctly:
Input fields of type number return values as strings. To ensure that the data sent to the API matches the expected types (numbers instead of strings), you need to parse these values before updating your state.
Submission to the API:
You need to implement the onSubmit function in the parent component that sends the inputData to the API endpoint. Once you receive a successful response, you can then navigate to the next page (e.g., EarlyCalculationPage.tsx) and display the results accordingly.
Let's go through each step in detail.
1. Adjusting StockInputPage.tsx
a. Parsing Numeric Values in handleInputChange:
Modify your handleInputChange function to parse numeric inputs correctly:
Make sure that your input fields have the correct name attributes corresponding to the keys in your inputData. For array inputs, you can omit the name attribute or handle it appropriately since you're updating the state based on index and arrayName.
c. Updating the Input Fields:
For your p_ejector and p_values input fields, ensure they are correctly set up:
tsx
{/* Rendering p_ejector inputs */}
<h3 className="input-label">Введите значения для p_ejector:</h3>
{inputData.p_ejector.map((value, index) => (
<input
key={`p_ejector-${index}`}
type="number"
placeholder={`p_ejector для части ${index + 1}`}
value={value}
onChange={(e) => handleInputChange(e, index, 'p_ejector')}
className="value-input"
/>
))}
In your parent component, you need to implement the onSubmit function passed to StockInputPage to handle the API call.
tsx
// ParentComponent.tsx (or equivalent)
import React from 'react';
import StockInputPage from './StockInputPage';
import { useHistory } from 'react-router-dom';
const ParentComponent = () => {
const history = useHistory();
const handleStockInputSubmit = async (inputData) => {
try {
const response = await fetch('YOUR_API_ENDPOINT_URL/calculate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(inputData),
});
if (!response.ok) {
throw new Error(`Ошибка HTTP: ${response.status}`);
}
const result = await response.json();
// Navigate to the results page with the result data
history.push('/results', { resultData: result });
} catch (error) {
console.error('Ошибка при отправке данных:', error);
// You might want to show an error message to the user here
}
};
return (
<StockInputPage
stock={selectedStock}
onSubmit={handleStockInputSubmit}
/>
);
};
export default ParentComponent;
Note: Replace YOUR_API_ENDPOINT_URL with the actual URL of your API endpoint.
3. Navigating to EarlyCalculationPage with Results
On successful API response, you can navigate to the EarlyCalculationPage.tsx and pass the result data using React Router's history.push.
In your EarlyCalculationPage.tsx, you can access the passed data:
tsx
// EarlyCalculationPage.tsx
import React from 'react';
import { useLocation } from 'react-router-dom';
const EarlyCalculationPage = () => {
const location = useLocation();
const { resultData } = location.state || {};
// Now you can use resultData to display your results
// ...
return (
<div>
{/* Render your results here */}
</div>
);
};
export default EarlyCalculationPage;
4. Handling Missing or Pre-Filled Data
If you need to pre-fill the form with existing data or prompt the user to fill in missing data, you can use the initialData prop in your StockInputPage.tsx.
In your useEffect, you've already set up the component to update inputData with initialData if it's provided:
Error Handling: Always include error handling for your API calls to handle situations where the API might fail or return an error.
Validation: Before submitting, you might want to validate the inputs to ensure all required fields are filled and have valid values.
User Feedback: Provide feedback to the user during loading states or if an error occurs. This improves the user experience.
Example Adjusted StockInputPage.tsx
Here's your StockInputPage.tsx with the adjustments:
tsx
Remember:
Always test your application after making changes to ensure everything works as expected.
Use browser developer tools to monitor network requests and check for any errors or issues with the data being sent or received.
Keep your components modular and handle side effects (like API calls) responsibly, preferably in the parent component or using effects/hooks designed for that purpose.
If you have any specific issues or errors you're encountering, please provide details, and I'll be happy to help you troubleshoot them further.