0
votes

I need to integrate with contentful, and am having a difficult time getting the nested JSON data

When i do this, i get the desired result:


  const client = contentful.createClient({
    space: '<space_id>',
    accessToken: '<access_token>'
  });

  useEffect(async () => {
    const response = await client.getEntry(id);
    setHeadLinks(response.fields.slug);
  }, []);

  console.log(headLinks);

I get a warning, though, in the console:

Warning: An effect function must not return anything besides a function, which is used for clean-up.

It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

So when i try it, i get an error message that response is not defined:

useEffect(() => {
    const fetchData = async () => {
      const response = await client.getEntry(id);
    };
    setHeadLinks(response.fields.slug);
    fetchData();
  }, []);

  console.log(headLinks);

Thank you for help

2

2 Answers

0
votes

You moved the call to setHeadLinks outside the function, and so the response variable is not in scope. Just need to move it back inside:

useEffect(() => {
  const fetchData = async () => {
    const response = await client.getEntry(id);
    setHeadLinks(response.fields.slug);
  };
  fetchData();
}, []);
0
votes

This is happening because response is defined inside the block of the async function. Try defining response outside the async function scope to take advantage of closures.

useEffect(async () => {
  let response;
  const fetchData = async () => {
    response = await client.getEntry(id);
  };
  await fetchData();
  setHeadLinks(response.fields.slug);  
}, []);

Take special notice that to do this you need to use let instead of const. You also have a problem with the use of async/await. See the corrected example and check the links below for more information about the topics mentioned.

https://developer.mozilla.org/en-US/docs/Glossary/Scope

https://developer.mozilla.org/es/docs/Web/JavaScript/Closures

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

This should fix your current error, but I don't know if it is enough for what you are trying to do.