I am trying to trigger a Button's loading state while waiting for API calls. This is my code below:
export default function JobAddPage() {
const [loading, setLoading] = useState(false);
async function handleSubmit() {
setLoading(true);
try {
// API Calls
} catch (error) {...}
setLoading(false);
}
return (
<LoadingButton loading={loading} onClick={handleSubmit}>Submit</LoadingButton>
);
}
The Code works but when I add the setLoading
hook inside handleSubmit
then I get the following error.
TypeError: Cannot read properties of null (reading 'state')
Are you not allowed to have useState hooks inside async functions in React? I've read this article: https://reactjs.org/docs/hooks-rules.html#explanation
I can get this code to work on class components, it seems fairly simple.
Thanks,
CodePudding user response:
Not sure but I think you should put your setLoading(true)
inside the try
block
CodePudding user response:
This is probably how you're loading the form itself. What I would suggest trying is this:
Change your onClick event to:
onClick{() => handleSubmit()}
You may console log your value to see what is going on.
CodePudding user response:
The code you posted is fine. But is is clear this is not the ACTUAL CODE. Can you post the missing parts? Include all your imports
as well as the full contents of the async method.
My guess is that the useState
method you are calling is not the useState
exported from React.