Home > Software engineering >  Can't access lexical definition of response before initialization within a React hook
Can't access lexical definition of response before initialization within a React hook

Time:08-02

I'm trying to make the home page send one API call on load and display all results on screen. It seems to send the call and receive response fine, although despite receiving the response from the server it can't pass the contents of the payload within the code, which is a JSON.

useEffect(() => {
        const localUser = localStorage.getItem("user");
        if (localUser) {
            const foundUser = localUser;
            setUser(foundUser);
        } else {
            const newUser = uuidv1();
            localStorage.setItem(newUser, user);
            setUser(newUser);
        }
        console.log(user);
        async function fetchPosts() {
            try {
                let tempPosts = [];
                const response = await fetch('http://localhost:3000/posts')
                    .then(response => response.json())
                    .then(response.payload.forEach(object => tempPosts.push(object.post)))
                    .then(setPosts((posts) => [tempPosts]));
                console.log(posts);
            } catch (err) {
                console.log(err)
            }
        }

        fetchPosts();

    }, [user, posts]);

Somehow React is trying to access the response without the declaration and I have no idea how, which in result stops the function from executing.

CodePudding user response:

Take a look at this line:

const response = await fetch('http://localhost:3000/posts')
                       .then(response => response.json())

You're combining two paradigms - asynchronous programming using Promises and callbacks with then, and asynchronous programming using async/await. You'll usually want to pick one or the other for use in a single function, and you definitely cannot combine them in a single line (or at least, not like this).

If you want to use async (and I would recommend this approach), you'll probably want something like this:

async function fetchPosts() {
    let tempPosts = [];
    const response = await fetch('http://localhost:3000/posts');
    const data = await response.json();
    data.payload.forEach(object => tempPosts.push(object.post))
    
    return tempPosts;
}

I don't know what data looks like, so you may have to play with the 4th line of the function, but hopefully you get the gist. You'll probably want to define this function outside of your component, and certainly not within the useEffect hook.

An example of how you could use this to fetch posts on the first render of your component is

useEffect(() => {
  fetchPosts().then(data => setPosts(data));
}, []);

assuming you have a relevant useState hook.

  • Related