简体   繁体   中英

How can I make a request to an API based on the response from another request? React Hook “useSwr” cannot be called inside a callback

I'm having trouble figuring out how I can make a request to an API based on the response from another request. I'm making a request to an API and extracting the IP address from the response.

Then I want to make another request to a different API using the IP address as input to the 2nd API. When I try the code below I get the error React Hook "useSwr" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function React Hook "useSwr" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function

I'm using React, TypeScript and SWR. I had this working with a simple JavaScript code but I think I'm getting confused with React/Typescript/SWR here. Is there a better way to accomplish what I'm trying to do?

import React, {FC} from 'react';
import useSwr from 'swr';

const fetcher = (...args: Parameters<typeof fetch>) => fetch(...args).then(response => response.json());

const Webmap: FC = () => {

  const validatorUrl = 'http://url1.com';
  const ipInfoUrl =  'http://url2.com';

  const {data, error} = useSwr(validatorUrl, fetcher);
  const validatorData = data && !error ? data : [];

  if (validatorData.results != null) {
    validatorData.results.forEach(u => {
    const ipAddress= u.ip_address
    console.log(ipAddress)
    // This is where I want to make another request. I want to feed ipAddress to ipInfoUrl
    const {data, error} = useSwr(ipInfoUrl, fetcher);
    const ipData = data && !error ? data : [];
    });
  }

Your are breacking a golden rule from hook definition:

https://reactjs.org/docs/hooks-rules.html

Here: https://swr.vercel.app/docs/conditional-fetching#dependent

import React, {FC} from 'react';
import useSwr from 'swr';

const fetcher = (...args: Parameters<typeof fetch>) => fetch(...args).then(response => response.json());

const Webmap: FC = () => {

  const validatorUrl = 'http://url1.com';
  const ipInfoUrl =  'http://url2.com';

  const { data: validationData, error: validationError } = useSwr(validatorUrl, fetcher);
  const { data: ipData, error: ipError } = useSwr(() =>
      // this request wont be called until validationData succeeds
      // use a data from validationData, example:
      ipInfoUrl + '?ip=' validationData.results.ip_address,
      fetcher
  );

  console.log(ipData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM