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

Categories

I'm doing an ssg website, it doesn't have backend, but it does start to have some features that fetch some data from another server. I checked the SWR and it works, the issue is I need to make a post request on button click, and it gets me an error:

hooks can only be called inside of the body of a function component

What I see is that I can create a function component, set up a call in it and just mount this component on button click, it works, but I'm having doubts about this approach. This is probably done to work with get request, but I make a post.

ExportComponent renders on a page or in another component.

function ExportComponent() {
  const [exportCalled, setExportCalled] = useState(false)
  const exportCall = () => {
    setExportCalled(true)
  }

  if (exportCalled) {
    return (
      <CallExport></CallExport>
    )
  }

  return (
    <Button
      onClick={ exportCall() }
    >
      Export
    </Button>
  );
}

function CallExport() {
  // api post call
  const { data, isLoading } = exportProject();
  if (isLoading) {
    return <CircularProgress />;
  }
  return (
    // call to api is done, make something with data
    <Button>Open</Button>
  )
}


export function exportProject() {
  const params = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({}),
  };
  const exportFetcher = (url) => fetch(url, params).then((r) => r.json());
  const { data, error } = useSWR('url', exportFetcher);
  return {
    data,
    isLoading: !error && !data,
    isError: error
  }
}
    

Is it wrong? Is there a better way?

question from:https://stackoverflow.com/questions/65907287/next-js-make-post-request-on-button-click-ssg

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

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...