Reputation: 91
I'm running a Next.js app in localhost:3000 that initially redirects to a login page if there is not user data. Initally it redirects to login page but it doesn't render and I get thrown this error:
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
in Index (at _app.js:7)
in ApolloProvider (at _app.js:6)
in MyApp
in ErrorBoundary (created by ReactDevOverlay)
in ReactDevOverlay (created by Container)
in Container (created by AppContainer)
in AppContainer
in Root
I'm not sure what I'm doing wrong. I'm new to Next.js and not sure how to deal with this.
Any help will be appreciated.
Here is my code:
import Layout from '../components/Layout';
import Client from '../components/Client';
import { useRouter } from 'next/router';
import { useQuery } from '@apollo/client';
import { queryGetClientsVendor } from '../graphql/queries';
import Link from 'next/link';
const Index = () => {
const router = useRouter();
const { data, loading, error } = useQuery(queryGetClientsVendor);
console.log(data, loading, error);
if (loading) return 'Loading...';
if (!data.getClientsVendor) {
return router.push('/login');
}
return (
<div>
<Layout>
<h1 className='text-2xl text-gray-800 font-normal'>Index</h1>
<Link href='/newclient'>
<a className='bg-blue-800 py-2 px-5 mt-5 inline-block text-white rounded text-sm hover:bg-gray-800 mb-3 uppercase font-bold'>
New Client
</a>
</Link>
<table className='table-auto shadow-md mt-10 w-full w-lg'>
<thead className='bg-gray-800'>
<tr className='text-white'>
<th className='w-1/5 py-2'>Name</th>
<th className='w-1/5 py-2'>Company</th>
<th className='w-1/5 py-2'>Email</th>
<th className='w-1/5 py-2'>Delete</th>
<th className='w-1/5 py-2'>Edit</th>
</tr>
</thead>
<tbody className='bg-white'>
{data.getClientsVendor.map((client) => (
<Client key={client.id} client={client} />
))}
</tbody>
</table>
</Layout>
</div>
);
};
export default Index;
You can also check the whole code project on github => https://github.com/francislagares/crm-react
Thanks in advance.
Upvotes: 1
Views: 3406
Reputation: 91
Well, after digging into Next docs I finally could make it work with getInititalProps:
Index.getInitialProps = async (ctx) => {
if (ctx && ctx.req) {
ctx.res.writeHead(302, { Location: '/login' });
ctx.res.end();
} else {
return {};
}
};
Thanks.
Upvotes: 0
Reputation: 66
You don't return router.push
- it not React child
.
I suggest you try with:
if (!data.getClientsVendor) {
router.push('/login');
return <p>Redirecting...</p>;
}
Thanks.
Upvotes: 2