question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Fetcher with an AWS signedRequest is not updating data

See original GitHub issue

Bug report

Description / Observed Behavior

useSWR is not updating data when using a custom fetcher:

  const request = { method: "GET", path: "/test" };

  const { data, error } = useSWR([request], fetcher);

Expected Behavior

To get data populated with the custom fetcher response.

Repro Steps / Code Example

My component:

import React, { memo, FC } from "react";
import { AmplifySignOut } from "@aws-amplify/ui-react";
import useSWR from "swr";

import fetcher from "./service/fetcher";

const AppWithRoutes: FC = () => {
  const request = { method: "GET", path: "/test" };

  const { data, error } = useSWR([request], fetcher);

  console.log("AppWithRoutes - data ===>", data);
  console.log("AppWithRoutes - error ===>", error);

  return (
    <>
      <AmplifySignOut />
      My AppWithRoutes
    </>
  );
};

export default memo(AppWithRoutes);

The custom fetcher:

import { Auth } from "aws-amplify";
import aws4 from "aws4";
import fetch from "unfetch";

import config from "../config";

const fetcher = (payload: any) => {
  Auth.currentCredentials()
    .then((currentCredentials) => {
      const credentials = Auth.essentialCredentials(currentCredentials);

      const apiGateway = {
        host: config.apiGateway.HOST,
        url: config.apiGateway.URL + payload.path,
      };

      const stage = config.apiGateway.URL.substring(
        config.apiGateway.URL.lastIndexOf("/") + 1
      );

      const request = {
        ...apiGateway,
        ...payload,
        path: `/${stage}${payload.path}`,
      };

      let signedRequest = aws4.sign(request, {
        // assumes user has authenticated and we have called
        // AWS.config.credentials.get to retrieve keys and
        // session tokens
        secretAccessKey: credentials["secretAccessKey"],
        accessKeyId: credentials["accessKeyId"],
        sessionToken: credentials["sessionToken"],
      });

      signedRequest.headers["Content-Type"] = "application/json";

      delete signedRequest.headers["Host"];
      delete signedRequest.headers["Content-Length"];

      // console.log("signedRequest *************>", signedRequest);

      return fetch(apiGateway.url, signedRequest).then(async (resp) => {
        const result = await resp.json();

        console.log(
          "signedRequest - result.response *************>",
          result.response
        );

        return {
          data: result.response,
          error: "",
          status: 200,
        };
      });
    })
    .catch((err) => err);
};

export default fetcher;

Additional Context

image

SWR version is: ^0.3.9

image

Note: I tried adding a return before Auth.currentCredentials() buuuut it causes an infinite loop of requests.

I also started a discussion here: https://github.com/vercel/swr/discussions/820

Thanks a bunch hackers!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6

github_iconTop GitHub Comments

3reactions
promer94commented, Dec 18, 2020
// move out the request object, so that it would not create a new object in every render
const request = { method: "GET", path: "/test" };
const AppWithRoutes: FC = () => {
  const { data, error } = useSWR([request], fetcher);

  console.log("AppWithRoutes - data ===>", data);
  console.log("AppWithRoutes - error ===>", error);

  return (
    <>
      <AmplifySignOut />
      My AppWithRoutes
    </>
  );
};

For more information https://swr.vercel.app/docs/arguments#passing-objects

1reaction
promer94commented, Dec 18, 2020
const fetcher = (payload: any) => {
  // It seems you miss the return statement here
  return Auth.currentCredentials().then(v => {
   ....
  })
Read more comments on GitHub >

github_iconTop Results From Across the Web

Updating Data - Amazon Forecast - AWS Documentation
Learn how to update data in Forecast. ... Forecast does not automatically retrain a predictor when you import an updated dataset, but you...
Read more >
mutate in useSWR hook not updating the DOM - Stack Overflow
js app and I populate the data using a useSWR hook. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus ...
Read more >
County of Los Angeles CHIEF EXECUTIVE OFFICE OPERATIONS ...
Probation – Karen Fletcher, Chief Deputy; David Grkinich, Bureau Chief; ... Healthcare Exchange LLC (GHX) for supply chain procurement and data management ...
Read more >
Tag: DevOps – Russell Ballestrini
AWS was presenting my root block device as /dev/nvme1n1 and my data … ... So autofs randomly stopped working on one of my...
Read more >
Graphql playground upload file - Liceo Sportivo
We need to write two separate data fetcher classes for the allBooks and Book ... File uploading is not part of the official...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found