0

im brand new to Next.js and i have the following situation. i want to redirect the user to the route /messages if he type route /messages/123 based on css media query so if he is mobile we will not redirect and if he in browser then redirect . i have tried the following code

import React, { useLayoutEffect } from 'react';
import { useRouter, push } from 'next/router';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import Layout from '../components/Customer/Layout/Layout';
import Chat from '../components/Customer/Chat/Chat';

const Messages = () => {
 const { pathname, push } = useRouter();
 const matches = useMediaQuery('(min-width:1024px)');

 useLayoutEffect(() => {
   console.log('I am about to render!');
   if (matches && pathname === '/messages') {
     console.log('match!');
     push('/');
   }
 }, [matches, pathname, push]);

 return (
   <Layout currentURL={pathname}>
     <Chat />
   </Layout>
 );
};

export default Messages;

the problem is the component render twice before redirect

1 Answers1

0

But You should probably be using useEffect since you are not trying to do any DOM manipulations or calculations.

useLayoutEffect: If you need to mutate the DOM and/or DO need to perform measurements

useEffect: If you don't need to interact with the DOM at all or your DOM changes are unobservable (seriously, most of the time you should use this).

You should see immediate action.

Edit:

You can use Next JS getInitialProps to check the request headers and determine if the request if from mobile or desktop then redirect from there.

getInitialProps({ res, req }) {
    if (res) {
      // Test req.headers['user-agent'] to see if its mobile or not then redirect accordingly
      res.writeHead(302, {
        Location: '/message'
      })
      res.end()
    }
    return {}
  }
Community
  • 1
  • 1
Karim
  • 415
  • 6
  • 14