I saved token into asyncstorage to be retrieved for authentication, but the problem is whenever i get the value, i log it into the console and it works but it doesn't send token to header, i have tried several method but all logic seems abortive. kindly help with your experience, or am I using the run asyncstorage?
export const editProfile = (userData) => {
const storageGet = async () => {
try {
const result = await AsyncStorage.getItem("token");
console.log("data", result);
console.warn("data", result);
return result;
} catch(error) {
console.log(error);
}
}
return (dispatch, getState) => {
const userId = getState().auth._id
axios.put(`${url}/users/${userId}`, userData,
(async () => { // block of code to set auth token to header
try{
const x = await storageGet()
console.log("nowToken", x) // it returns the token into the console
setHeaders(x) // but didn't set the token in the header
}catch(err) {
console.log(err.response)
}
})()
// setHeaders(token)
)
.then(response => {
dispatch({
type: "EDIT_PROFILE_SUCCESS",
username: response.data.username,
email: response.data.email,
name: response.data.name,
phoneNumber: response.data.phoneNumber,
biography: response.data.biography,
gender: response.data.gender,
address: response.data.address,
message: response.data.message,
success: response.data.success
})
})
.catch((error) => {
console.log(error.response)
})
}
}
CodePudding user response:
From the axios doc, the api is axios.put(url[, data[, config]])
your 3rd parameter (representing the config) is a function that isn't returning anything. Replace it with a function that returns the config object you want. e.g. ()=>{'authorization': await AsyncStorage.getItem("token")}
That should do the trick.
This may be more readable.
const token = await AsyncStorage.getItem("token")
const config = {headers: {'authorization':`bearer ${token}`}}
axios.put(`${url}/users/${userId}`, userData, config)
edit snippet was missing 'headers' key.