2

I am extremely excited about using contentful for my project, but I can't get the JS library to work in a react-native project.

I get the following error: enter image description here

I have tried the following approaches:

import contentful from 'contentful'; 
// or
var contentful = require('contentful');

You can reproduce the bug by going to this repo and following the steps I have provided.

Help would be greatly appreciated.

Daniel Apt
  • 2,468
  • 1
  • 21
  • 34

3 Answers3

2

I am maintaining the Contentful sdk. I've put together a simple example that shows how to use the SDK in React Native, you can check it here It is basically getting a list of items from one of our example spaces and display the names in a ListView.Check indes.ios.js. It looks like there is something wrong with the caching in your machine or so. Anyway I hope this helps.If you have more problems please feel free to create issues in our github page

[UPDATE]

you can now configure the axios instance used in the SDK to use a different adapter. You can pass that when calling createClient

adapter: config => {
    config.adapter = null // this is important if it is passing to another axios instance
    // an http client combatible with React Native
    return fetch(config)
  }

Best,

Khaled

Khaled Garbaya
  • 1,479
  • 16
  • 20
  • 2
    Hey Khaled -- it seems contentful sdk no longer works with react native, because it uses Node modules, which are rejected by expo. – Deroude Apr 30 '18 at 12:49
  • Any chance this project is still maintained? If so can you verify it is working on your end? The repo has no directions and does not build for me currently. In fact, I have not found another RN project that uses Contentful anywhere. Thanks – jasonleonhard Jan 28 '19 at 19:02
  • @Deroude : Have you find a way to work it in react-native i am using right now using 3.6.4 which working with react-native but latest version of contentful has issue with dependecy while we run react-native project. – Bhavesh Jariwala Jun 05 '19 at 07:03
  • @KhaledGarbaya: can you confirm that latest version of contentful is working with react-native or not.? – Bhavesh Jariwala Jun 05 '19 at 07:05
  • did you use my the provided solution and still didn't work. ? – Khaled Garbaya Jun 05 '19 at 14:20
  • @Bhavesh -- sorry mate, we dropped contentful altogether, not necessarily for this issue. – Deroude Jun 12 '19 at 10:09
  • I just tried using Expo with Contentful. Unfortunately, it still doesn't work. I commented on a post in stackoverflow https://github.com/contentful/contentful.js/issues/361 – Hendry Lim Apr 05 '20 at 01:41
  • Hey, the example repo is using "react-native": "0.34.1". It doesn't seem to work with the latest React Native version anymore. Could we have an updated repo/boilerplate? – Waltari Jan 12 '22 at 07:19
  • This it the error I'm getting with React Native 0.66.3 "error: Error: Unable to resolve module assert from /Users/user/veri/app/node_modules/contentful/dist/contentful.node.js: assert could not be found within the project or in these directories:" – Waltari Jan 12 '22 at 07:20
0

I've tried every option and it will never work using the Contentful SDK.

However, you can get it with REST and transform the response using the types from the contentful lib.

import axios from 'axios';
import {EntryCollection} from 'contentful';

import Env from '../Env';

const contentfulApi = 'https://cdn.contentful.com';

/**
 * Default locale used in contentful calls
 *
 * @see {@link getContentfulEntries}
 * @constant
 */
export const ContentfulLocale = 'sv';

/**
 * @typedef ContentfulProps
 * @param locale optional locale to use. Default is {@link ContentfulLocale}
 * @param entryType content type in contentful model
 */
type ContentfulProps = {
  entryType: string;
  locale?: string;
};
/**
 * Get entries from Contentful content API
 * @param props See {@link ContentfulProps}
 */
export const getContentfulEntries = async <T>(
  props: ContentfulProps,
): Promise<EntryCollection<T>> => {
  const client = axios.create({
    baseURL: `${contentfulApi}/spaces/${Env.CONTENTFUL_SPACEID}/environments/master/entries?`,
    timeout: 1000,
    headers: {Authorization: `Bearer ${Env.CONTENTFUL_TOKEN}`},
  });

  const result = await client.get<EntryCollection<T>>(
    '&content_type=' + props.entryType,
  );

  return result.data;
};

export default getContentfulEntries;
Thomas Hagström
  • 4,371
  • 1
  • 21
  • 27
0

I think the best way to use Contentful APIs with React Native is to use Apollo client and graphQL packages. I worked around the same and get it done.

  • Install Apollo client and GraphQL npm package

npm install @apollo/client graphql

  • Install react-native async storage to store cache

npm install @react-native-async-storage/async-storage

  • Install apollo cache persist to persist the cache

npm install apollo3-cache-persist

you can read apollographql official documents for implementation

  • Create ApolloClient in the app.tsx/.js file

import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';

const cache = new InMemoryCache();

const client = new ApolloClient({
  uri: 'https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}',
  cache,
  credentials: 'same-origin',
  headers: {
    Authorization: `Bearer {CDA-Access-Token}`,
  },
});
  • Wrap all components in ApolloProvider

const App = () => {
  const [loadingCache, setLoadingCache] = useState(true);

  useEffect(() => {
    persistCache({
      cache,
      storage: AsyncStorage,
    }).then(() => setLoadingCache(false));
  }, []);

  if (loadingCache) {
    return <Loader />;
  }

  return (
    <ApolloProvider client={client}>
      <SafeAreaView style={{flex: 1}}>
        <Posts />
      </SafeAreaView>
    </ApolloProvider>
  );
};
export default App;
  • Import gql and useQuery to fetch data

import { gql, useQuery } from '@apollo/client';

  • Now, write GraphQL query

const QUERY_COLLECTION = gql`
  {
    postsCollection {
      items {
        title
        author
        publishDate
        inshorts
        featuredImage {
          url
        }
      }
    }
  }
`;
  • Fetch data using useQuery function

const { data, loading } = useQuery(QUERY_COLLECTION);

That's all to fetch data from Contentful in React Native App. To read this in detailed, have a look to this post