Though the clientToken
has been defined and assigned a value, it is showing undefined properties, why?
The API call has been working fine, the URL is fine, but still it showing this error, can anyone help me with this.
Below is the error detial.
if (info && info.error) {
26 | setInfo({ ...info, error: info.error });
27 | } else {
> 28 | const clientToken = info.clientToken;
| ^ 29 | setInfo({ clientToken });
30 | }
31 | });
getToken object is below.
const getToken = (userId, token) => {
getmeToken(userId, token).then(info => {
// console.log("INFORMATION", info);
if (info && info.error) {
setInfo({ ...info, error: info.error });
} else {
const clientToken = info.clientToken;
setInfo({ clientToken });
}
});
};
getmeToken component below.
export const getmeToken = (userId, token) => {
return fetch(` ${API}/payment/gettoken/${userId}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
}
}).then(response => {
return response.json();
})
.catch(err => console.log(err))
}
Can anyone help me with this?
CodePudding user response:
In your else
condition you're never checking if info
has been defined and it most likely isn't. The issue probably doesn't come from clientToken
itself but from info
being undefined
or null
.
You can try to do something like this:
if (info) {
if (info.error) {
setInfo({ ...info, error: info.error });
} else {
const clientToken = info.clientToken;
setInfo({ clientToken });
}
}
CodePudding user response:
If you want set data from API to state, you must rewrite getToken
method. Get error
, clientToken
options from response and set it to state. setInfo((prev) => { ...prev, clientToken });
const getToken = (userId, token) => {
getmeToken(userId, token).then(res => {
if (res) {
const { error, clientToken } = res;
error && setInfo((prev) => { ...prev, error });
clientToken && setInfo((prev) => { ...prev, clientToken, error: ''
})
}
});
};