Search code examples
javascriptreactjscontent-management-systemgraphcmshygraph

How to get my posts from Hygraph to show them on my React app


I want to connect my react app with hygraph, to show my posts on the page. I have problem with writing http request, I got such example from chatgpt:

import React, { useState, useEffect } from 'react';

const YourComponent = () => {
  const [data, setData] = useState([]);
  const apiUrl = 'myApiUrl';
  const apiToken = 'myApiToken';

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${apiToken}`,
          },
          body: JSON.stringify({
            query: `
              query Komunikaty {
                komunikaty {
                  date
                  id
                  publishedAt
                  title
                }
              }
            `,
          }),
        });

        const result = await response.json();
        setData(result.data.komunikaty);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Your CMS Data</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>
            <strong>{item.title}</strong> - {item.publishedAt}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default YourComponent;

But the response is response

What should I do to get my posts?

Thank you

I have been trying to do this with axios but didn't get any results, also I have tryiedto do this with Apollo and I also didn't get the result


Solution

  • I found the problem. I did console.log(result) and I saw 403 error "Not allowed", so I created new permission for all models and I have deleted HTTP request header Authorization: `Bearer ${apiToken}`,. Now it works.