1

I'm trying to get JSON data from an s3 bucket using React (in a Gatsby project).

This is my code.

import React from 'react';


function getJson() {
    return fetch("http://secstat.info/testthechartdata.json")
    .then((response) => response.json())
    .then((responseJson) => {
      return <div>{responseJson[0]}</div>;
    })
    .catch((error) => {
      console.error(error);
    });
 };


 export default getJson;

This is the error I get.

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

How should I do this? There is probably an easy way to do this in Gatsby but I was going to use React.

1 Answer 1

4

Your code has 2 issues:

  1. You can't return a component that waits to Promise.
  2. Fetching a cross domain assets will require CORS headers in your S3

You should refactor it to something like this:

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

function getJson() {
  return fetch('http://secstat.info/testthechartdata.json')
    .then(response => response.json())
    .catch(error => {
      console.error(error);
    });
}

const MyComp = () => {
  const [list, setList] = useState([]);

  useEffect(() => {
    getJson().then(list => setList(list));
  }, []);

  return (
    <ul>
      {list.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
export default MyComp;

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain what the code s doing? @felixmosh
Gatsby works with React Components, therefore, you need to return one. I've used useEffect & useState react hooks which you can read here reactjs.org/docs/hooks-intro.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.