0

I try to update the "submissions" state variable using useEffect() hooks that is supposed to fetch data from API. But after I do setSubmissions(result.data) and then pass submissions variable to Table component <Table data={submissions} /> it results in an error TypeError: Cannot convert undefined or null to object, which tells me that I'm not successfully updating submissions variable to an array from API fetching.

export default function Dashboard() {
    const [submissions, setSubmissions] = useState([]);
  
    useEffect(() => {
      async function loadData() {
        const query = `query {submissionsList {
           user_id type quantity impact date}
          }`;
        const response = await fetch ('http://localhost:8000/graphql', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json'},
          body: JSON.stringify({ query })
        });
        const result = await response.json()
        setSubmissions(result.data);
      }
      loadData();
    }, []);
  
    return (
        <Grid container spacing={4}>
          <Grid item xs={12}>
            <Widget>
              <Table data={submissions} />
            </Widget>
          </Grid>
        </Grid>)}
  • What results from logging `result`? it seems to me that the api is responding with `undefined`. – GhostOrder Nov 27 '21 at 00:57
  • @GhostOrder for some reason console.log works outside of `useEffect()` hook, but does not record anything within it. – Valeriy Ivanov Nov 27 '21 at 02:12
  • You need to console.log `result` from inside `useEffect`, because `result` is within the useEffect scope, it doesn't exist outside of it. – GhostOrder Nov 27 '21 at 02:29
  • Agree, but for some reason `console.log` inside `useEffect` is not working... – Valeriy Ivanov Nov 27 '21 at 02:31
  • did you tried to log other data like a plain string just to test if the problem is console.log? (which I doubt but just in case), or try to log `result` + a string like `console.log('this is the result' + result)`. Btw, Is react notifying you of some errors? Other possibility is your server maybe is responding with an empty string. – GhostOrder Nov 27 '21 at 02:41
  • Ok, console.log worked (not sure what the bug was). – Valeriy Ivanov Nov 28 '21 at 03:03
  • You may want to add a `catch` clause to your fetch to help capture errors, especially for debugging. The first answer here is a good example: https://stackoverflow.com/questions/51859358/how-to-read-json-file-with-fetch-in-javascript – Ed Lucas Nov 29 '21 at 00:46

2 Answers2

0

Two things - 1) use a try catch block for errors; and 2) check what the response is returning

export default function Dashboard() {
const [submissions, setSubmissions] = useState([]);

useEffect(() => {
    async function loadData() {
        try {
            const query = `query {submissionsList {
            user_id type quantity impact date}
           }`;
            const response = await fetch('http://localhost:8000/graphql', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ query })
            });
            console.log(response);
            setSubmissions(response.data); // change this based on the response, you may or may not need to call json() on it

        } catch (error) {
            console.error(error);
        }
    }
    loadData();
}, []);

return (
    <Grid container spacing={4}>
        <Grid item xs={12}>
            <Widget>
                <Table data={submissions} />
                </Widget>
            </Grid>
        </Grid>
    );
}
antipodally
  • 474
  • 3
  • 5
0

I got this same issue when i used fetch but when i switched it to axios to fetch it worked fine

Ahmusa118
  • 1
  • 3
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 22 '22 at 19:15