Выполните GET и затем POST onSubmit внутри функции React - PullRequest
0 голосов
/ 29 апреля 2020

После заполнения формы и нажатия кнопки Отправить я хотел бы, чтобы функция React выполняла GET, а затем POST после завершения GET. Каков наилучший способ справиться с этим? Вот функция только с GET:

import React, {useState} from 'react';
import './App.css';
import { useForm } from 'react-hook-form';
import {Link} from 'react-router-dom';

function GPfSOA({ match }) {

  const [item, addItem] = useState([]);

  const { register, handleSubmit, errors } = useForm();

  const onSubmit = async (data) => {
    const fetchItem = await fetch(`http://localhost:3001/alignments/getpoint/${match.params.id}/${data.station}/${data.offset}`);
    const item = await fetchItem.json();
    addItem(item);
    console.log(item);
    console.log(match.params.id, data.station, data.offset);
  }

  return (
    <div>
      <ul align="left">
        <h1><Link to={`/alignments/${match.params.id}`}>{match.params.alignment}</Link></h1>
        <h2>Enter Station and Offset to get the Point WKT</h2>
      </ul>
    <form onSubmit={handleSubmit(onSubmit)}>
      <ul align="left">
        <label>Station:</label>
        <input name="station" ref={register({ required: true })} />
        {errors.station && <span>This field is required</span>}
      </ul>
      <ul align="left">
        <label>Offset: </label>
        <input name="offset" ref={register({ required: true })} />
        {errors.offset && <span>This field is required</span>}
      </ul>
      <ul align="left">
        <input type="submit" />
      </ul>
      <ul>
        <h2 align="left">Back to the <Link to={`/alignments/${match.params.id}`}>{item.alignment}</Link> alignment</h2>
      </ul>
    </form>
    {Object.entries(item).map(([key, val]) => (
      <ul align="left" key={key}>
        <h3>{key}: {val}</h3>
      </ul>
    ))}
    <ul align="left">
      {item.x && <h3><a target="_blank" rel="noopener noreferrer" href={`http://40.121.36.110/?t=${item.alignment}_Alignment_Grid_500_3857.qgs&hc=1&crs=EPSG:2274&s=500&c=${item.x},${item.y}`}>Show point in new QWC2 Web Map</a></h3>}
    </ul>
    <ul align="left">
      {item.x && <h3><Link to={`/alignments/getalsfromxy/${item.x}/${item.y}`}>Alignments that contain the Point {item.x},{item.y}}</Link></h3>}
    </ul>
    <ul align="left">
      {item.x && <h3><Link to={`/alignments/getsegsfromxy/${item.x}/${item.y}`}>Alignment segments that contain the Point {item.x},{item.y}}</Link></h3>}
    </ul>
    <ul align="left">
      {item.x && <h3><Link to={`/alignments/ptso/post/create`}>Store new point</Link></h3>}
    </ul>
  </div>
  )
}

export default GPfSOA;

console.log(item) и console.log(match.params.id, data.station, data.offset) оба показывают правильные результаты.

Я перепробовал много вещей, включая добавление этого в onSubmit:

const doSomething = await fetch('http://localhost:3001/alignments/ptso/post/create', {
method: 'POST',
headers: {
    'Content-Type': 'text/plain'
},
body: JSON.stringify({
    ptx: item.ptx,
    pty: item.pty,
    station: data.station,
    offset: data.offset,
    alid: match.params.id,
    alname: item.alignment
  })
}).then(res => {
  console.log(JSON.stringify({
    ptx: item.ptx,
    pty: item.pty,
    station: data.station,
    offset: data.offset,
    alid: match.params.id,
    alname: item.alignment
  }))
    return res.json()
})
.then(data => console.log('Success:', data))
.catch(error => console.log('Error:', error))

, но я получаю сообщение об ошибке, что item.ptx не определен. Как только GET завершается, item.ptx получает значение. Затем он может запустить POST.

Я также пытался использовать useEffect безрезультатно.

...