0
import Link from 'next/link'

export const getStaticProps = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  const data = await res.json();

  return {
    props: { ninjas: data }
  }
}

const Ninjas = ({ ninjas }) => {
  // console.log(ninjas)

  return (
    <div>
      <h1>All Ninjas</h1>
      {ninjas.map(ninja => (
        <Link href={'/ninjas/' + ninja.id} key={ninja.id}>
          <a>
            <h3>{ ninja.name }</h3>
          </a>
        </Link>
      ))}
    </div>
  );
}
 
export default Ninjas;

this is my code, how can I solve this error, I want to map data of json place holder to be map. I have tried a lot but it is not solving. I want to implement dynamic routing in next js. I am new in it. please help me

4
  • What's the output of the commented console log? Commented Jul 18, 2021 at 15:58
  • ninjas is undefined before it returns from the async call. Check for undefined ninjas before you try to map it. Return null or some loading info instead of your map when ninjas is undefined. Commented Jul 18, 2021 at 15:58
  • Code working fine in codesandbox.io/s/jovial-hooks-g2bnd?file=/pages/index.js Commented Jul 18, 2021 at 16:00
  • @ajmnz it is running but on localhost it is not running Commented Jul 18, 2021 at 17:30

2 Answers 2

1

I think the problem is that you're trying to call the map function on the data before it has been fully loaded, you can use a ternary operator to make sure your code only runs once you have the data

{!ninjas ? "loading..." : ninjas.map(ninja => (
        <Link href={'/ninjas/' + ninja.id} key={ninja.id}>
          <a>
            <h3>{ ninja.name }</h3>
          </a>
        </Link>
      ))}
Sign up to request clarification or add additional context in comments.

Comments

0

It appears that your data function is not returning data. You need to check if the data is set in the getStaticProps function and return notFound if it is not set.

Since your call is in getStaticProps you do not need to check if the data is available on your page. This is because pages without all the required props i.e. {ninjas}) will never successfully build (will result in a 404 page).

 const res = await fetch('https://jsonplaceholder.typicode.com/users');
 const data = await res.json();

  if (!data) {
    return {
      notFound: true,
    }
  }
  return {
    props: { ninjas: data }
  }
}

Note - You could have hit your request limits for the API which would explain why the code works for some and not you. To valid this theory - look at the network request tab in your browser and see if you are getting denied. You still need to return notFound in your getStaticProps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.