Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

639
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda