0

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?

Felix
  • 55
  • 9
  • 2
    Well, you basically just built yourself a custom hook (https://reactjs.org/docs/hooks-custom.html). You should prepend it with *use*. But the error baffles me. I think the approach is fine, but if you do the data fetching only in one component, you should do it directly there. – Gh05d Jan 26 '21 at 20:55

0 Answers0