Search code examples
reactjsaxiosuse-effect

UseEffect not fetching data with axios


I want to do a query to my database when I first land on a results page. I want to fetch some data from the database and I provide an id on the front-end via axios like this.

import { useEffect } from "react";
import axios from "axios";

const Results = ({ linkURL, surveyId }) => {

    const linkToShare = linkURL;

    useEffect(() => {
        axios.get(`/get-questions/${surveyId}`);
    }, []);

    return (
        <>
            <h1>Results page</h1>
        </>
    );
};

export default Results;

On the Back-End I am not getting any request and it doesn't show anything when refreshing on the page. At least I should be able to see the req.params.

app.get("/get-questions/:survey", (req, res) => {
    console.log("Route working", req.params);
});

I think it's not a problem with the params but with useEffect because I am not being able to make any connection with the server on this route. Tried several routes without params and nothing. Can't see anything logged on the console. Axios is working fine on other routes. Any idea what went wrong here?

EDIT

Inspecting the network tools I see this. The line above is a post request that works fine. The second one is my get to the server that's not working. Even if I am getting a 200.

enter image description here

enter image description here


Solution

  • After looking at all the debug information you provided I can tell you that the request is performed correctly. The next step are:

    1. Try to send something in the response: then, always in Network, when you click on the Preview you should see the body of your response.

    This is just an example:

    enter image description here

    1. If you can see the response properly, the next step is just to update the UI:
    import { useEffect, useState } from "react";
    import axios from "axios";
    
    const Results = ({ linkURL, surveyId }) => {
    
        const linkToShare = linkURL;
        const [question,setQuestion] = useState('');
    
        useEffect(() => {
            axios.get(`/get-questions/${surveyId}`)
    .then(res=>setQuestion(res.data.question)); //instead of .question use your JSON structure
        }, []);
    
        return (
            <>
                <h1>{`Question ${surveyId}:`}</h1>
                <p>{question}</p>
            </>
        );
    };
    
    export default Results;