flatlogic / react-material-admin

☄️React Material Admin is a React template built with Material-UI
https://flatlogic.com/admin-dashboards/react-material-admin/demo
MIT License
1.6k stars 559 forks source link

Calling external API for login #21

Closed afattahi54 closed 4 years ago

afattahi54 commented 4 years ago

This is a question not an issue :)

I like the design patterns and code structure of this admin dash board ( Using React Context, React Hooks, Material UI Theme modification and lot more ). I want to follow the project coding structure as much as I can.

I started to call APIs in this dash board and add hook base fetch approach ( I used SWR) .

First place to call API login functionality.

So, I have add API call to the UserContext.js file and changed loginUser function.

function loginUser(dispatch, login, password, history, setIsLoading, setError) { 
....useSWR('/api/login'); ...

But I face the error:

React Hook "useSWR" is called in function "loginUser" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks

If I want to have a correct design pattern, how can I fix it. The "loginUser" seemed the best place for calling login APIs but it seems that I can not put it here.

Thanks 😀

michaeldaineka commented 4 years ago

Hi! You can't just push React Hooks inside primary JavaScript functions. You can either create your own custom function hook or use React Component functions.

So you can easily create useSWR function and put within your React Hook And then put calling of the function right into loginUser.

Best regards