i am new to react native i am trying to store the generated token from API to a storage so I can access it from anywhere in my application the generated token Is available in response.data.token i want to store it in something like session storage or local storage to access it from
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(response => {
alert(JSON.stringify(response.data.token));
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
also pls let me know how i can check for if the token is stored in React Native debugger
You have to use #react-native-async-storage/async-storage library to store the token in LocalStorage.
After that use it like this.
import AsyncStorage from '#react-native-async-storage/async-storage';
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(response => {
alert(JSON.stringify(response.data.token));
AsyncStorage.setItem('token', JSON.stringify(response.data.token));
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
Actually there is no exact way to check that token is available in the LocalStorage or not but you can console.log() it and check.
For checking it.
useEffect(() => {
const getUserToken = async () => {
const token = await AsyncStorage.getItem('token');
console.log("token",token)
};
getUserToken();
}, []);
You can use Redux to Store the Session Token
and with useSelector you can access token all over the app .
You can go through with these documentations
Link 1
Link 2
If you just want to save some data in an unsecured way and access it from anywhere, then yes, Async Storage is your option.
Just install the Async Storage like that:
yarn add #react-native-async-storage/async-storage
And then in any async function, you can call this to set data:
await AsyncStorage.setItem('your_data_identifier', data);
And call this to get data:
const data = await AsyncStorage.getItem('your_data_identifier');
More here https://react-native-async-storage.github.io/async-storage/
If you want a more secure way, there are a few libs, like this for example:
https://github.com/talut/rn-secure-storage
Related
I have the following problem when I request data from the Spotify API, at first I get it, but when I reload the page or try to write this state using useState, an error 400 or 401 occurs. The code I use to get the data:
`
import axios from 'axios';
const BASE_URL = 'https://api.spotify.com/v1';
export const fetchFromAPI = async (url: string, token: string) => {
const { data } = await axios.get((`${BASE_URL}/${url}`), {
method: 'GET',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return data;
}
`
Next, I use the fetchFromAPI function:
`
const { token } = useContext(Context);
const [albums, setAlbums] = useState<string[]>([]);
useEffect(() => {
fetchFromAPI('browse/new-releases', token)
.then((data) => console.log(data));
}, [token])
`
I've tried logging out of my account and back in, I've also tried other links to get data but it's always the same problem. I also checked if the token is present before requesting the data and it is
Ok, I managed to find and solve this error myself.
The error was that I didn't have a user token yet, but useEffect was already starting to receive data.
useEffect(() => {
if (token) {
fetchNewReleases();
fetchFeaturedPlaylists();
fetchCategories();
fetchRecommendations();
} else {
console.log('error');
}}, [token])
For example, this piece of code will print an error twice, and only after that I receive a token and can receive data from the API.
To be honest, I didn't know how to run useEffect only when I have a token, so I solved it in a simpler way, but I don't know if it's completely correct, I have the following condition Object.values(state).length) !== 0 and if it is true, only then will I display the data from the API
I am trying to pull a jwt out of a loginUser mutation and store it in a variable then use the apollo-link to setContext of the header via "Authorization: Bearer ${token} for authentification as all my other mutations and queries require the token. I have been slamming the docs for days on Apollo Client(React) -v 3.3.20. I have been through all the docs and they show all these examples of client.readQuery & writeQuery which frankly seem to just refetch data? I don't understand how you actually pull the data out of the response and store it in a variable.
The response is being stored in the cache and I have no idea how to take that data and store it in a token variable as I stated above. Which remote queries I can just access the returned data via the data object from the useQuery hook, however on the useMutation hook data returns undefined. The only thing I could find on this on stack overflow was the my data type may be custom or non-traditional type but not sure if that is the problem.
[Cache in apollo dev tools][1]
[Mutation in apollo dev tools][2]
[Response in network tab][3]
Here is my ApolloClient config:
const httpLink = createHttpLink({ uri: 'http://localhost:4000/',
// credentials: 'same-origin'
});
const authMiddleware = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('token');
// add the authorization to the headers
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
authorization: `Bearer ${token}` || null,
}
}));
return forward(operation);
})
const client = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, httpLink),
});
The header works obviously I just can't grab the token to pass so the header just sends Authorization: Bearer.
For the login I have this:
const LOGIN_USER = gql`
mutation($data:LoginUserInput!) {
loginUser(
data: $data
) {
user {
id
name
}
token
}
}
`;
const [loginUser, { data, loading, error }] = useMutation(LOGIN_USER);
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
Originally I was just calling
onClick={loginUser( { variables })}
For the login but onComplete never works and everywhere I look I see lots of posts about it with no solutions. So I tried slamming everything into a function that I then called with loginUser inside it:
const submit = async () => {
loginUser({ variables})
// const { user } = await client.readQuery({
// query: ACCESS_TOKEN,
// })
// console.log(`User : ${JSON.stringify(user)}`)
const token = 'token';
const userId = 'userId';
// console.log(user);
// localStorage.setItem(token, 'helpme');
// console.log({data});
}
At this point I was just spending hours upon hours just trying mindless stuff to potentially get some clue on where to go.
But seriously, what does that { data } in useMutation even do if it's undefined. Works perfectly fine for me to call data.foo from useQuery but useMutation it is undefined.
Any help is greatly appreciated.
[1]: https://i.stack.imgur.com/bGcYj.png
[2]: https://i.stack.imgur.com/DlzJ1.png
[3]: https://i.stack.imgur.com/D0hb3.png
I followed thistutorial and i was able to create view for github:
if i put social auth token, i am able to retrieve the original token.
I am looking for ways to implement this process inside vuejs.
can i do something similar to this:
onGoogleSignInSuccess (resp) {
const token = resp.Zi.access_token
axios.post('http://localhost:8000/auth/google/', {
access_token: token
})
.then(resp => {
this.user = resp.data.user
})
.catch(err => {
console.log(err.response)
})
},
I am trying to add Twilio Chat to my react native project. I'm getting an error with the name SyncError and code 0. I'm just trying to confirm it's connected at this point. Here's my basic setup.
Import at the top
import {Client as Chat} from 'twilio-chat'
Inside my class
componentDidMount = async () => {
console.log(Chat);
const token = await AsyncStorage.getItem('auth-token');
axios.get(config.apiUrl + '/chat/details', { headers: { Authorization: token } })
.then(res => {
console.log(res);
Chat.create(res.data.twilioToken)
.then(client => {
console.log('client', client);
this.subscribeToAllChatClientEvents(client);
})
.catch(error => {
console.log('There was an error', error);
});
})
.catch(err => {
console.log(err);
})
}
The error also mentions an "Unhandled promise rejection" but I've included any catch blocks where needed.
Thanks for any help.
For anyone getting the same issue. I realised that the problem was in my server code as I wasn't creating the twilio jwt token properly.
There's likely a problem with the token.
In my experience, I got a good token from my backend server and I save it on AsyncStorage. However, after a while the token wasn't working anymore.
I solved it by requesting the server a new twilio token each time I needed to instantiate the SDK client.
I am using Apollo (with Graph Cool), redux, and Auth0 in a React-Native app. I am trying to delay the queries and mutations until the header is set.
The idToken is stored in Async Storage, and is therefore a promise. I can't use redux to pass the token, because that would create a circular dependency.
When the user logins in for the first time or the token has expired, the queries are sent before header is set, which means I get the error Error: GraphQL error: Insufficient Permissions
How can I delay the queries until the token is found and added to the header? I have been searching three main solutions:
Add forceFetch: true; This seems to be part of an earlier implementation of the Apollo client. Even if I find the equivalent, the app still fails on the first attempt to fetch.
Reset the store (rehydrate?) upon logging in. This is still asynchronous so I don't see how this could affect the outcome.
Remove all mutations and queries from login itself, but due to the progress of the app, this is not feasible.
Some snippets:
const token = AsyncStorage.getItem('token');
const networkInterface = createNetworkInterface({ uri:XXXX})
//adds the token in the header
networkInterface.use([{
applyMiddleware(req, next) {
if(!req.options.headers) {
req.options.headers = {}
}
if(token) {
token
.then(myToken => {
req.options.headers.authorization = `Bearer ${myToken}`;
})
.catch(err => console.log(err));
}
next(); // middleware so needs to allow the endpoint functions to run;
},
}]);
// create the apollo client;
const client = new ApolloClient({
networkInterface,
dataIdFromObject: o => o.id
});
and
const store = createStore(
combineReducers({
token: tokenReducer,
profile: profileReducer,
path: pathReducer,
apollo: client.reducer(),
}),
{}, // initial state
compose(
applyMiddleware(thunk, client.middleware(), logger),
)
);
I'm not certain this will work without a reproduction app, mostly because I don't have an app of your structure set up, but you're hitting this race condition because you are calling next() outside of your async chain.
Calling next() where it is currently will tell the client to continue on with the request, even if your token isn't set. Instead, let's wait until the token comes back and the header gets set before continuing on.
networkInterface.use([{
applyMiddleware(req, next) {
if(!req.options.headers) {
req.options.headers = {}
}
AsyncStorage.getItem('token')
.then(myToken => {
req.options.headers.authorization = `Bearer ${myToken}`;
})
.then(next) // call next() after authorization header is set.
.catch(err => console.log(err));
}
}]);