1

I'm having hard time on thinking how will I populate hooks with API response(json)

see below codes

cosnt [loginResponse, setloginResponse] = useState({
    Token: '',
    UserID: '', //from user-id
    UserName: '', //from user-userName
    firstName: '', //from user-firstName
    rcCode: '' //from attributes-rcCode 
})

const login = async () => {
    await axios.get('/API')
        .then(response => {
            console.log('response.data', response.data.resp)
        });
}

here's the result of console.log(response.data.resp)

{
    "data": {
        "token": "abcd",
            "user": {
            "id": "123456",
            "userName": "uname",
            "firstName": "FNAME",
            "lastName": "MNAME",
            "email": "[email protected]",
            "attributes": {
                "favorites": ["FAV"],
                "rcCode": ["123"]
            },
            "requiredActions": [],
            "roles": ["ROLE"]
        },
        "modulePermissions": []
    }
}

for console.log(response.data):

"resp": {
    "data": {
        "token": "abcd",
        "user": {
            "id": "123456",
            "userName": "uname",
            "firstName": "FNAME",
            "lastName": "MNAME",
            "email": "[email protected]",
            "attributes": {
                "favorites": ["FAV"],
                "rcCode": ["123"]
            },
            "requiredActions": [],
            "roles": ["ROLE"]
        },
        "modulePermissions": []
    }
},
"success": true

I want to populate my hooks with those datas for me to utilize it on my page.

I got undefined if I tried to console.log(response.data.resp.data)

On console.log(response), I got:

enter image description here

Thank you.

4
  • When you post code, validate it first. Commented Mar 16, 2021 at 10:00
  • Hi @zhulien, are you referring to the format? My apologies, I will make it more formatted next time. Commented Mar 16, 2021 at 10:04
  • No, neither your response json nor the function that did the request were valid. Commented Mar 16, 2021 at 10:06
  • hi @zhulien, can you help me with my question Commented Mar 17, 2021 at 5:38

2 Answers 2

3

Don't use async/await and .then() together. Use either of those.

const login = async () => {
    const response = await axios.get('/API');
    const parsedData = JSON.parse(response.data.resp);
    const userData = parsedData.data;

    setLoginResponse({
        Token: userData.token,
        UserID: userData.user.id,
        UserName: userData.user.userName,
        firstName: userData.user.firstName,
        rcCode: userData.user.attributes.rcCode
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Sir i tried and put console.log before setLoginresponse but I got undefined
Hi @rajiv-punjabi, I got this error Unhandled Rejection (TypeError): Cannot read property 'token' of undefined. I also tried to console.log the userData, but I got undefined
Are you sure you are getting a proper response from backend services? Based on your demo data it works properly. Playground Demo
Hi @rajiv-punjabi, I updated my question with the screenshot of console.log(response) . THank you
Remove const userData line and replace with this. const parsedData = JSON.parse(yourResponse.resp.data); const userData = parsedData.data;
|
0

In the .then

setLoginResponse({...loginResponse, Token: response.data.resp.data.token, UserId: response.data.resp.data.user.id, ...}

You can destructure your response object first and store values in variables to make the setLoginResponse more easy to read.

https://reactjs.org/docs/hooks-state.html

7 Comments

Hi @alaric, upon console.log I can't access response.data.resp.data. And for response.data.resp.data.token i got error Unhandled Rejection (TypeError): Cannot read property 'token' of undefined
@Rymrk , you are trying to access this value in .then right ? Just try to log your resp and check if there is data inside or another object, maybe you have typo in your api or forgot something and remove the useless async await
Hi @alaric, I stated the return of console.log above.
Check Rajiv Punjabi response above, I haven't noticed the async/await sorry about that, you can't mix both in your case, use promise or async await as you prefer
Can you edit your post with your correct login function please ?
|

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.