0

I am trying to set the state from an async API call and then dynamically render some JSX based on the returned data.

The problem is, I think the state is being set only after the JSX has already rendered, and since it is in an a useEffect hook with a dependency( "[]" ) it only renders on the initial load. Therefore, the map in the JSX does not run.

I know the API is returning the correct data, as I can tell from the console.log but not sure where to go from here? I've tried adding the workspaces variable as a dependency to the useEffect hook but that just causes an infinite loop. Any ideas?

export const WorkspaceToggle = () => {
 
    const [workspaces, setWorkspaces] = useState([])

    useEffect(() => {

      (async () => {
        
        const data = await getUserWorkspaces()
        setWorkspaces(data)
        console.log(data)
        
      })();

    }, []);
    
    return (
      <>
        <Container>
          <DropdownCon>
            <DropdownToggle>{dropdownText}</DropdownToggle>
            <DropdownMenu>
              
              {workspaces.map((space: any) => {
                
                <DropdownItem eventKey="1">{space.name} Workspace</DropdownItem>
                
              }) as ReactNode}
              
            </DropdownMenu>
          </DropdownCon>
        </Container>
      </>
    )
  }


0 Answers0