Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

reactjs - Calling my Custom Fetch Components Directly Without Having to use a useState based variable

I am still learning React JS, so, I dont know if this is the way React JS works (so, I am doing it the right way), or I am doing the wrong way, and hence need some help.

I am using a three layer network abstraction for making fetch calls.

First, here is my raw network call making component.

export function useFetch(uri: string, something?: string, getThetoken?: any, 
  setrequesttype?: string,body? : Object,triggerapi? : string) {
  const [data, setData] = useState();
  const [error, setError] = useState();
  const [loading, setLoading] = useState(true);

  //by default we assume a GET request
  var requesttype = "GET";

  if (setrequesttype !== undefined) {
    requesttype = setrequesttype;
  }

  useEffect(() => {
    if (!uri) return;
    if (something === "authorized" && !getThetoken) return;
    fetch(uri, {
      method: requesttype,
      headers: {
        Authorization: `Bearer ${getThetoken}`,
      }
    }
    )
      .then(data => data.json())
      .then(setData)
      .then(() => setLoading(false))
      .catch(setError);
  }, [uri, something, getThetoken,requesttype,triggerapi]);

  return {
    loading,
    data,
    error
  };
}

Here is my middle layer for networking. A middleman between components and the above useFect network calling component.

const Fetch: FC<FetchProps> = ({
    uri,
    renderSuccess,
    loadingFallback = <p>---</p>,
    renderError = (error: any) => (
        <div>
        </div>            
    ),
    something,
    getThetoken,
    setrequesttype,
    body,
    triggerapi
}: FetchProps) => {
    console.log("inside Fetch");
    const { loading, data, error } = useFetch(uri, something, getThetoken,setrequesttype,body,triggerapi);
    if (loading) return loadingFallback;
    if (error) return renderError(error);
    if (data) return renderSuccess({ data });
}

export default Fetch;

I built these components, and they work just fine. However, I do run into issues, like this. Here is a component that is able to successfully use it.

const RandomQuote = () => {
  const [something, setsomething] = useState("hello");

  function changeSomething() {
    if (something === "bird") {
      setsomething("hello");
    } else {
      setsomething("bird");
    }
  }
  return (
    <Fragment>
      <RandomQuoteHelper something={something} />
      <Button color="primary" onClick={changeSomething}>
        {buttondisplaystring}
      </Button>
    </Fragment>
  );
};

export default RandomQuote;

and here is the RandomQuoteHelper which makes the call to the api, and renders the result.

function RandomQuoteHelper({ something }: RandomQuoteHelperProps) {
  //TODO - these things should be coming from a config file
  const baseURL = "https://localhost:44372";
  const endPoint = "/api/UserNotLoggedIn/GetHoldOfthem";
  var url2 = baseURL + endPoint;
  //manually set the request type
  const setrequesttype = "GET";

  return (
    <Fetch 
      uri={url2} 
      renderSuccess={QuoteDetails} 
      something={something} 
      setrequesttype = {setrequesttype}/>
  );
}

The above code works, and I get to call my API just fine. Unfortunately, I have to use the function 'changeSomething' to force a state change, which then calls the Fetch/useFetch components.

In the current form, the button click cannot directly call my network components. Not unless a dependent value is forcibly changed. I built it this way, by using a react js book. The author lady, built it this way, which suited her example perfectly. However, now, as I work on an actual project, it does not seem like the best approach. That means, throughout my project, anytime i want to trigger a api call, I have to keep using this 'changeSomething' type setup.

So, is there any way, I can directly call my fetch component?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...