0

I'm trying to use a database I set up in a headless cms known as contentful. The problem is, all the tutorials I watched uses Class components to handle state. I learned useContext for the Context API method, which I find to be more appealing and less of a headache. I know how to request data from conetextful, but I don't know how to use the data outside of the use of a Class component. I suppose one question I could ask is whether it's even possible to use contentful with an object or function component?

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router} from 'react-router-dom';
import App from './App';
import 'w3-css';
import {BsyndContext} from './context/bsyndContext';
import Client from './Contentful';

Client.getEntries().then(res => console.log(res.items))

ReactDOM.render(
<BsyndContext.Provider value={"data here"} > 
 <Router> 
    <App />
    </Router>
  </BsyndContext.Provider>
 ,
  document.getElementById('root')
);

Fatemeh Qasemkhani
  • 1,942
  • 1
  • 15
  • 25
FINAL BOSS
  • 15
  • 1
  • 6

1 Answers1

1

Create a BsyndProvider wrapper component and inside it, make api call(in useEffect) and get your content and store it in the state. Pass the content to value prop.

import Client from './Contentful';
export default const BsyndContext = React.createContext({});


export const BsyndProvider = (props) => {
    const [value,setValue] = useState({});

    useEffect(() => {
        Client.getEntries().then(res => setValue(res.items))
    }, []);

    return (
      <BsyndContext.Provider value={value}>
        {props.children}
      </BsyndContext.Provider>
    );
}

Wrap your application inside the BsyndContext.Provider.

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router} from 'react-router-dom';
import App from './App';
import 'w3-css';
import {BsyndProvider} from './context/bsyndContext';


ReactDOM.render(
  <BsyndProvider> 
    <Router> 
        <App />
    </Router>
  </BsyndProvider>
 ,
  document.getElementById('root')
);

Use context(your content) in your component like this:

function App() {
  const myContent = useContext(BsyndContext);

  return (
    <div>
      {myContent.Heading}
    </div>
  );
}

gdh
  • 13,114
  • 2
  • 16
  • 28