Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

633
Views
Cant fetch data. Error: Can't set headers after they are sent to the client

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 })
}
about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report

0

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 })
    }
about 4 years ago · Santiago Gelvez Report

0

I figured out what the problem was.

While my main issue was the component not rendering the data on the page due to fetching the wrong login route on the client side. When the user is logging in, I stored the user Id on local storage and retrieve the user Id from local storage to fetch for the user's id when rendering the user's post.

The issue on the server side was due to not returning on the if statement and led to returning 2 response.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!