✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Discussion on importing a link from a database to a project using Next.js and client.fetch

12 replies
Last updated: Jul 28, 2022
Hey guys! I want to import a link from my database to the project. What is the easiest and quickest way to do it?
Jul 26, 2022, 1:23 AM
This doesnt seem to work:
Jul 26, 2022, 2:04 AM
const query = ‘*[ _type == “users” ]{linkTree, walletAddress}’ client.fetch(query)
console.log(linkTree)
Jul 26, 2022, 2:04 AM
client.fetch
returns a promise. You need to
.then
it or
await
it.
Jul 26, 2022, 7:55 AM
user F
I was able to console.log and it’s reading it . Now I need to send it to the link statement so the user can access the custom link
Jul 26, 2022, 6:52 PM
To where ‘/’ is displayed
Jul 26, 2022, 6:53 PM
Mornin’ Sanity! Hope you guys are doing well. Can someone check this thread and help me to figure how to export the fetch to the statement?
Jul 27, 2022, 3:13 PM
It’s going to depend a lot on which framework you’re using.
Jul 27, 2022, 3:15 PM
user F
I’m using next.js right now. I have tried everything and nothing is really working at all.
Jul 27, 2022, 3:15 PM
Alright, in Next.js you’d do your query in
getStaticProps
and you would pass down the props to your component.
Jul 27, 2022, 3:16 PM
user F
did you look at the NextJS docs and tutorials? They are really good 😉
As an example from their
data fetching site :
// A very useful library 😉
import { groq } from "next-sanity";


// this 👇 is your page
function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.

// This is your data fetching 👇
export async function getStaticProps() {

  // You would use groq here to get your sanity data
  const res = await fetch(YOUR_QUERY)
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

export default Blog
Hope that helps
🙂
Jul 28, 2022, 7:26 AM
I actually used these tutorials and they really helped me with understanding it. However I had to do a little bit of a mix with another method because for some reason it was giving me an undefined, so I put what’s supposed to be ‘getStaticProps()’ under a class and then on a useEffect.
Jul 28, 2022, 1:01 PM
Thank you
user F
user J
superstars 🔥🔥
Jul 28, 2022, 1:03 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?