0

Yet another question concerning a JSON object whose key's values are undefined. So I make this request:

const update = async (
  endpoint,
  body = null,
  jwt_token = null,
  header = { "Content-Type": "application/json" }) => {

  let opt = header;
  if (jwt_token){
      opt["Authorization"] = jwt_token
  }

  try {
    return await axios.patch(BASE_URL + endpoint, body, { headers: opt })
  } catch (err) {
    console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);
  }
}

const handleUpdate = async ({ username, email }) => {
    const token = Cookies.get("token");
    const body = { user: { username: username, email: email } };
    const response = await update(`/users/${currentUser.id}`, body, token);
    console.log(response);
    if (response.status === 200) {
        handleChange(response);
    }
};

Which give me this JSON object (which is a JSON object, I have no doubt, it is not a JSON formated string that should be parsed, as one can see in the response's header):

// response's data
{
    "data": {
        "id": "1",
        "type": "user",
        "attributes": {
            "email": "[email protected]",
            "username": "mamie",
            "admin": false
        },
        "relationships": {
            "activities": {
                "data": [
                    {
                        "id": "1",
                        "type": "activity"
                    },
                    {
                        "id": "2",
                        "type": "activity"
                    }
                ]
            }
        }
    }
}
// response's header
HTTP/2 200 OK
server: nginx
date: Tue, 20 Jul 2021 14:23:02 GMT
content-type: application/json; charset=utf-8
x-sso-wat: You ve just been SSOed
access-control-allow-origin: *
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
access-control-expose-headers: 
access-control-max-age: 7200
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
x-download-options: noopen
x-permitted-cross-domain-policies: none
referrer-policy: strict-origin-when-cross-origin
etag: W/"***"
cache-control: max-age=0, private, must-revalidate
x-request-id: ***
x-runtime: 0.068777
vary: Origin
content-security-policy: upgrade-insecure-requests
content-security-policy-report-only: default-src https: data: 'unsafe-inline' 'unsafe-eval'
permissions-policy: interest-cohort=()
strict-transport-security: max-age=63072000; includeSubDomains; preload
X-Firefox-Spdy: h2

The issue being, I get undefined when I try to access response.data.attributes (and its content, email or username for example). Yet, I can access response.status, since the condition response.status === 200 works, and I should add that I have the whole object when I console.log(response). There, I can see that I have the appropriate data, I just can't access it with Javascript.
What I have already tried :

  • parsing the response, but got an error since it already is a JSON object -> content-type: application/json; charset=utf-8 in the response's header. So I tried JSON.parse(JSON.stringify(response)) : didn't change anything from the initial problem
  • making sure my Rails API returns me a JSON (yes it does : render json: UserSerializer.new(@user).serializable_hash.to_json, status: :ok)
  • making sure there is no character encoding issue : I don't think so, everything is encoded in UTF-8 (in the response's header there is content-type: application/json; charset=utf-8, in my IDE, and in the index.html I have <meta charset="UTF-8" />)

I do not have such issue with other pieces of code making get or post requests.

2
  • Can you access response.data.type and get the expected output? If so then your response simply doesn't include response.data.attributes. Commented Jul 20, 2021 at 15:10
  • No I cannot access response.data.type. I should add in the question that I have the whole object when I console.log(response). There, I can see that I have the appropriate data, I just can't access it with Javascript. Commented Jul 20, 2021 at 15:16

1 Answer 1

2

Axios returns an object with items such as status, statusCode, loading etc... One of those is data which contains the response data from your endpoint. Your backend looks to be returning a data object also.

So your answer should be to read response.data.data.attributes. A bit messy I realise but maybe you can change your backend to not wrap the response in data also.

Sign up to request clarification or add additional context in comments.

2 Comments

OMG this is it, thanks !! Its been three days I'm on this haha ...
Glad to hear it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.