reactjs - IDに基づいて反応で2つのJSON APIを結合する方法

CorePress2024-05-09  2

How to combine two json apis in react based on id

ID 値に基づいて 2 つの JSON API を結合しようとしています。それを達成する方法はありますか? ありがとう。以下は、私がこれまでに試みたコードのセクションです。

  const [data, setdata] = useState([])
  const [runs, setruns] = useState([])

  //get data from the first api
  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axios.get('http://localhost:8000/tasks?format=json');
        setdata(res.data['results']);
      } catch (e) {
        console.log(e)
      }
    }
    fetchData();
  }, []);

  //map the rows of data from the api above to obtain values based on id value
  useEffect(() => {
    data.map(row => {
      console.log(row.id)
      const fetchRuns = async () => {
        const res2 = await axios.get(`http://localhost:8000/task/${row.id}/runs`);
        setruns(res2.data)
      }
      fetchRuns();
      row.rundata = runs
      console.log('row:', row)
    })
  }, []);


-----------------------------------

最初の useEffect で 2 番目のリクエストを作成し、すべてをまとめて保存することもできます。

useEffect(() => {
  const fetchData = async () => {
    try {
      const res = await axios.get('http://localhost:8000/tasks?format=json'); 
      const arr = [];     
      res.data.result.map(row => {
        arr.push(axios.get(`http://localhost:8000/task/${row.id}/runs`));
      }

      const res2 = await axios.all(arr);
      setdata(); // here you will need to join both results, but to help you better we will need the structure of both
    } catch (e) {
      console.log(e)
    }
  }
  fetchData();
}, []);


-----------------------------------

私の理解が正しければ、最初に ID のリストを提供する API 呼び出しがあり、2 番目の API 呼び出しに基づいてそれらの IDS からデータを入力 (データを取得) する必要があります。

2 番目の useEffect の依存関係に「データ」を渡す必要があります。これにより、React に「'data' が変更されるたびに、次のことを実行してください」と指示されます。

また、ループの最後にデータを設定する必要があります。そうしないと、反復ごとに 1 つの値で変更することになります。

とにかく、非同期ロジックは .map と互換性が低いため、おそらく「for await」構文を使用する必要があります。

const [data, setdata] = useState([])
const [runs, setruns] = useState([])

useEffect(() => {
const fetchData = async () => {
  try {
    const res = await axios.get('http://localhost:8000/tasks?format=json');
    setdata(res.data['results']);
  } catch (e) {
    console.log(e)
  }
}
fetchData();
}, []);


async function populate(data){
 let populatedData = []
 for await (let row of rows){
   const res2 = await axios.get(`http://localhost:8000/task/${row.id}/runs`)
   populatedData.push(res2.data)
  }
  setruns(populatedData)
 }
   
useEffect(() => {
 if (data.length === 0) return
 populate(data)
},[data])

それがうまくいくかどうか教えてください!



-----------------------------------

Your guide to a better future - quark24
Your guide to a better future - quark24