Call hook only if prop that it requires exist if not return default values

Viewed 440

In Next.js during SSR I get user object from session and ip address of client that performed request.

 return {
   props: {
     user,
     ipAddress,
   },
 };

User can exist but it can also be undefined if request is unauthenticated. I want to be able to:

  1. If user is authenticated run react-query hook that uses user.id and fetches user settings.
  2. If user is not authenticated provide default settings values that I have stored in config file.
const LandingPage = ({
  user,
  ipAddress,
}: LandingPageProperties): JSX.Element => {
  
  // User exist

  const { config } = useGetOwnSettingsQuery(
    {
      endpoint: 'http://localhost:3000/api/graphql',
      fetchParams: {
        headers: setFetchHeaders(),
      },
    },
    { userWhere: { id: user?.id } },
  );

  // User does not exist

  imported config from config.ts

  return <LandingPageMap className="map" { config goes here }/>;
};

I really dont have good idea how to perform what I want, hooks do not like if I call them inside useEffect and they dont like if I return early to check if user exist.

2 Answers

So, I guess I get your point, if user exist (means if the props is not undefined) then fetch config else use the default one right?

If you think this can will be used in other places in your application then I suggest go for building your own hook.

Ref: https://reactjs.org/docs/hooks-custom.html

function useUserConfig({user}) {

let [config, setConfig] = useState(defaultConfig) 

useEffect(() => { 
//...
setConfig(..code ) 
}, [user])

}

Then in your app, you can use it

let config = useUserConfig(props.user)

Solved by introducing one more component that receives filtered id. Then that component fetch data and render authenticated version of needed component.

const LandingPage = ({
  session,
  ipAddress,
}: LandingPageProperties): JSX.Element => {
  const id = session?.user.id;
  return (
    <Fragment>
      {id ? (
        <AuthenticatedMap id={id} ipAddress={ipAddress} />
      ) : (
        <LandingPageMap
          className="map"
          ipAddress={ipAddress}
          config={{ storage: appOptions.storage, plugins: appOptions.plugins }}
        />
      )}
    </Fragment>
  );
};
Related