Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Receiving undefined instead of JSON

I am using React axios to receive the JSON (array of objects) from server (server side is written on Go, I checked via Postman, JSON is sent properly).

Here is how I get the data on client side:

export const getPostData = async () => {
    const URL = 'http://localhost:8083/test'
    try {
        const { data: { data }} = await axios.get(URL);
        console.log(data)
        return data;
    } catch (error) {
        console.log(error)
    }
};

And this is how the getPostData is called in App.js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const App = () => {
  const [ posts, setPosts ] = useState([]);

  useEffect(() => {
    getPostData()
      .then((data) => {
        setPosts(data)
        console.log(data)
      })
  },[]);

The problem is I get undefined in browser console. I found many similar questions asked here, but I could not find the solution (the Access-Control-Allow-Origin header is set when I send the JSON).

What should I learn more, where could be the problem? I would be very grateful for any help!

If this could be helpful, here is how I send the JSON in Go:

    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Content-Type", "application/json")
    c.JSON(http.StatusOK, gin.H{
        "message": "Hello",
    })

>Solution :

This looks suspect:

const { data: { data }} = await axios.get(URL);

That tries to read a property called data from an object on the data property of the response from axios, like this without the destructuring:

const data = (await axios.get(URL)).data.data;

Your Go code doesn’t look like it puts a {"data": ___} wrapper around what it sends, and Axios only adds one layer of {data: ___} wrapper to what it gives you in the response, not two.

If you want the object from the JSON response, remove the inner destructuring:

const { data } = await axios.get(URL);

data will be {message: "Hello"} assuming the Go code sends the JSON {"message": "Hello"}.


Separately, your JavaScript code seems to expect an array of posts, but your Go code is just sending {"message": "Hello"}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading