User switch between Organization

Here is another attempt to switch organizations

In my use case when a user has logged in, I list all the organizations the user belongs to, so you can switch organizations via buttons (The button for each organization should call a function that receives the org_id).

You can get all the organizations via management api /api/v2/users/{id}/organizations

As users don’t have the same roles across all organizations, we need to update the session in order to get the new roles, so you can use the loginWithPopup function and pass in the organization you want to switch here’s an example code to do that

const { user, isAuthenticated, isLoading, loginWithPopup } = useAuth0();
  const [organizations, setOrganizations] = useState([]);
  const switchOrganization = async (org_id) => {
    loginWithPopup({
      organization: org_id
    })
  }
  
  useEffect(() => {
    if (isAuthenticated) {
      const sub = user.sub;
      try {
        fetch(`https://YOUR-AUTH0-API/api/v2/users/${sub}/organizations`, {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer YOU CAN GET A TESTING TOKEN FROM A M2M APPLICATION'
          }
        }).then((d) => d.json()).then((d) => {
          setOrganizations(d)
        });
      } catch (error) {

      }
    }
  }, [isAuthenticated, user])

This is to map over organizations state and render the buttons

{
          organizations.length ? organizations.map(o => (
            <button style={{ background: o.branding.colors.primary }} onClick={()=>{
              switchOrganization(o.id)
            }}>
              <img src={o.branding.logo_url} width='25' height='25' alt='' />
              Go to {o.display_name}
            </button>
          )) : null
        }