👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Migrating from Sanity version 2 to 3, encountering issue with using the sanity client in a React function.

1 replies
Last updated: May 24, 2023
I am migrating from version two version three and I’m running into a problem with the sanity client. It used to just look like this.
import sanityClient from 'part:@sanity/base/client';
Now we have to use the react hook from this

import {useClient} from 'sanity'
But the problem is when I try to do something like this

const client = useClient({apiVersion: '2023-05-24'});
I get an error because react hooks cannot be used at the top level

React Hook “useClient” cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.
The issue is that my previous code isn’t using the sanity client in a react function or component. It’s just using it at top level
May 24, 2023, 8:20 PM
It depends on where you’re doing this, but most of the methods within the Studio receive a
context
in its props that contains a client you can use.
May 24, 2023, 8:47 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?