Skip to content
Advertisement

UseEffect only works after refresh the page

I am using an useEffect inside a Context. I think the useEffect should run after load the page, but it does not work, but if I refresh the page(F5) then it works.

I am new Using React, but I think it should work with the empty array as arg.

This is the Context:

JavaScript

EDIT:

Now I realized that the problem is the useEffect render the first time in the login page (before I need it, because I need it after the login page), this is happening because PatientProvider is parent of all the components even Login component, but now I do not know how to set this provider to only “after login components”.

Here is my Routes:

JavaScript

Advertisement

Answer

It seems like your token is not set by the time the component mounts and calls this useEffect().

I can think of 2 options:

  1. store your session data in an outer context state and get the token from there. Then you can add token as a dependency in useEffect():
JavaScript
  1. Subscribe to localStorage in this component. react-hookz lib has a nice hook already written, providing it here for simplicity:
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement