-1

I am working on a front end of a project and I am stuck for a while. I have created an api with django rest framework and I am trying to connect to a Nextjs front end. The data is to show on the front page that is why I call getInitialProps. Following is the code

import styles from '../styles/Home.module.css';

import axios from 'axios';

const Home = ({ listings, error }) => {
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }
  return (
    <ul>
      {listings.map((listing) => (
        <li key={listing.address}>{listing.title}</li>
      ))}
    </ul>
  );
};

Home.getInitialProps = async (ctx) => {
  try {
    const res = await axios.get('http://127.0.0.1:8000/api/listings/?page=4');
    const rep = await res.data;
    console.log(rep.results);
    listings = rep.results;

    return { listings };
  } catch (error) {
    return { error };
  }
};

export default Home;

In the console log I get the data, which is in the bellow format:

[
  {
    index: 1734112,
    user: 11233,
    title: 'Classical style',
    address: 'address 23, city , country',
    bedrooms: '2',
    bethrooms: '1',
    price: '5803',
    list_type: 'rent'
  },
  {
    index: 1722303,
    user: 32119,
    title: 'Pangrati On the Lake',
    address: 'address 28, city , country',
    bedrooms: '1',
    bethrooms: '1',
    price: '4800',
    list_type: 'rent'
  }
]

But I get an error occured in the browser without specifying the error.

And in the console I get the bellow.

next-dev.js?3515:32 Warning: Did not expect server HTML to contain the text node "listings is not defined" in <div>.
    at div
    at Home (webpack-internal:///./pages/index.js:50:26)
    at MyApp (webpack-internal:///./pages/_app.js:38:27)
    at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:20584)
    at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:23125)
    at Container (webpack-internal:///./node_modules/next/dist/client/index.js:359:9)
    at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:793:26)
    at Root (webpack-internal:///./node_modules/next/dist/client/index.js:915:27)

I am not sure what the issue is so any help much appreciated. Thank you!

Peter Gould
  • 73
  • 1
  • 7
  • Have you looked at [this](https://stackoverflow.com/questions/45350360/react-16-warning-warning-js36-warning-did-not-expect-server-html-to-contain-a) ? – Arun T Feb 02 '22 at 10:52

1 Answers1

1

You are assigning value to some variable listings = rep.results;, but this variable was not declared, you can't do that in strict mode (which I believe is default in that case)

So just declare it as const and the error should go away:

const listings = rep.results
Danila
  • 15,606
  • 2
  • 35
  • 67