简体   繁体   中英

A JSON object key's return undefined in ReactJS

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": "mamie@email.com",
            "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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM