Home > Mobile >  Cant fetch data. Error: Can't set headers after they are sent to the client
Cant fetch data. Error: Can't set headers after they are sent to the client

Time:06-14

Im getting this error when I try to retrieve posts from a specific user. The code to fetch the data is correct. Not sure what the error is coming from.

From server side enter image description here Client Side

enter image description here

Below is the code for the individual post.

const UserPosts = () => {
    const [user, setUser] = useState()


    useEffect(() => {
        const id = localStorage.getItem("userId");
        const sendRequest = async () => {
            const res = await axios.get(`/post/user/${id}`)
                .catch(error => console.log(error));
            const data = await res.data;
            console.log(data)
            return data;

        }

        sendRequest()
            .then((data) => {
                setUser(data.user)
                console.log(data)
            })
    }, [])


    return (
        <div>
            {user &&
                user.posts.map((post, index) => (
                    <Post
                        id={post._id}
                        isUser={true}
                        key={index}
                        username={user.username}
                        caption={post.caption}
                        selectedFile={post.selectedFile}
                        createAt={post.createAt}
                    />
                )).reverse()}
        </div>
    )
}

export default UserPosts;

This is the post controller for that route

export const getUserById = async (req, res) => {
    const userId = req.params.id;

    let userPosts;
    try {
        userPosts = await User.findById(userId).populate("posts");
    } catch (error) {
        console.log(error)
    }
    if (!userPosts) {
        res.status(404).json({ message: "No Post Found" })
    }
    res.status(200).json({ user: userPosts })
}

CodePudding user response:

useEffect(() => {
        const id = localStorage.getItem("userId");
        const sendRequest = async () => {
            const {data} = await axios.get(`http://localhost:backend-port/post/user/${id}`)

            setUser(data.user)
        }

        sendRequest()
    }, [])

Please try that out

CodePudding user response:

Your problem, as @Gavin points out, is that you respond with a status of 404, but then fall through, out of the if block, to another res.status call. You can't send the status more than once like that, and you must restructure your logic to prevent prevent calling res.status twice. Two easy viable solutions:

Option 1: Add a return in the error-handling block to prevent falling through to the non-error case.

    if (!userPosts) {
        res.status(404).json({ message: "No Post Found" })
        return;
    }
    res.status(200).json({ user: userPosts })

Option 2: Use an else block to separate error-case from non-error case in a symmetric way.

    if (!userPosts) {
        res.status(404).json({ message: "No Post Found" })
    } else {
        res.status(200).json({ user: userPosts })
    }

CodePudding user response:

I figured out the problem. I had the wrong post request when user logged in which ended with a wrong user id, therefore, the post data wasn't being fetched correctly.

  • Related