Use custom hook in callback or in a function - javascript

I have:
rules={{
required: 'This is required.',
validate: (value) => daoExists(value),
}}
with daoExists, I need to check GraphQL endpoint and if it returns true, validation succeeds, otherwise some error message. I am using useQuery hooks from Apollo client for such queries, but now I have a problem, because daoExists can't be a hook. So, what I am doing is I create a daoExists as normal function. Something like this:
export const daoExists = async (name: string): Promise<ValidateResult> => {
const query = `
query Daos($name: String) {
daos(where: {name: $name}){
id
}
}
`;
const data = await fetch(subgraphUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query,
variables: { name: name },
}),
});
const daos = await data.json();
return daos?.data?.daos?.length > 0 || 'Dao with this name already exists';
};
Which I really don't like to use fetch and I want to continue using useQuery hooks, but I can't. I even tried creating useCallback, but then I can't use useQuery in my useCallback.
Are there any workarounds?

Related

How i can set globally auth token in axios? [duplicate]

I have a react/redux application that fetches a token from an api server. After the user authenticates I'd like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google.
Here is my redux setup:
// actions.js
import axios from 'axios';
export function loginUser(props) {
const url = `https://api.mydomain.com/login/`;
const { email, password } = props;
const request = axios.post(url, { email, password });
return {
type: LOGIN_USER,
payload: request
};
}
export function fetchPages() {
/* here is where I'd like the header to be attached automatically if the user
has logged in */
const request = axios.get(PAGES_URL);
return {
type: FETCH_PAGES,
payload: request
};
}
// reducers.js
const initialState = {
isAuthenticated: false,
token: null
};
export default (state = initialState, action) => {
switch(action.type) {
case LOGIN_USER:
// here is where I believe I should be attaching the header to all axios requests.
return {
token: action.payload.data.key,
isAuthenticated: true
};
case LOGOUT_USER:
// i would remove the header from all axios requests here.
return initialState;
default:
return state;
}
}
My token is stored in redux store under state.session.token.
I'm a bit lost on how to proceed. I've tried making an axios instance in a file in my root directory and update/import that instead of from node_modules but it's not attaching the header when the state changes. Any feedback/ideas are much appreciated, thanks.
There are multiple ways to achieve this. Here, I have explained the two most common approaches.
1. You can use axios interceptors to intercept any requests and add authorization headers.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
const token = store.getState().session.token;
config.headers.Authorization = token;
return config;
});
2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
So in your case:
axios.defaults.headers.common['Authorization'] = store.getState().session.token;
If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.
(function() {
String token = store.getState().session.token;
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
axios.defaults.headers.common['Authorization'] = null;
/*if setting null does not remove `Authorization` header then try
delete axios.defaults.headers.common['Authorization'];
*/
}
})();
Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).
Create instance of axios:
// Default config options
const defaultOptions = {
baseURL: <CHANGE-TO-URL>,
headers: {
'Content-Type': 'application/json',
},
};
// Create instance
let instance = axios.create(defaultOptions);
// Set the AUTH token for any request
instance.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
Then for any request the token will be select from localStorage and will be added to the request headers.
I'm using the same instance all over the app with this code:
import axios from 'axios';
const fetchClient = () => {
const defaultOptions = {
baseURL: process.env.REACT_APP_API_PATH,
method: 'get',
headers: {
'Content-Type': 'application/json',
},
};
// Create instance
let instance = axios.create(defaultOptions);
// Set the AUTH token for any request
instance.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
return instance;
};
export default fetchClient();
The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.
import axios from 'axios';
const client = (token = null) => {
const defaultOptions = {
headers: {
Authorization: token ? `Token ${token}` : '',
},
};
return {
get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
};
};
const request = client('MY SECRET TOKEN');
request.get(PAGES_URL);
In this client, you can also retrieve the token from the localStorage / cookie, as you want.
Similarly, we have a function to set or delete the token from calls like this:
import axios from 'axios';
export default function setAuthToken(token) {
axios.defaults.headers.common['Authorization'] = '';
delete axios.defaults.headers.common['Authorization'];
if (token) {
axios.defaults.headers.common['Authorization'] = `${token}`;
}
}
We always clean the existing token at initialization, then establish the received one.
The point is to set the token on the interceptors for each request
import axios from "axios";
const httpClient = axios.create({
baseURL: "http://youradress",
// baseURL: process.env.APP_API_BASE_URL,
});
httpClient.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
If you want to call other api routes in the future and keep your token in the store then try using redux middleware.
The middleware could listen for the an api action and dispatch api requests through axios accordingly.
Here is a very basic example:
actions/api.js
export const CALL_API = 'CALL_API';
function onSuccess(payload) {
return {
type: 'SUCCESS',
payload
};
}
function onError(payload) {
return {
type: 'ERROR',
payload,
error: true
};
}
export function apiLogin(credentials) {
return {
onSuccess,
onError,
type: CALL_API,
params: { ...credentials },
method: 'post',
url: 'login'
};
}
middleware/api.js
import axios from 'axios';
import { CALL_API } from '../actions/api';
export default ({ getState, dispatch }) => next => async action => {
// Ignore anything that's not calling the api
if (action.type !== CALL_API) {
return next(action);
}
// Grab the token from state
const { token } = getState().session;
// Format the request and attach the token.
const { method, onSuccess, onError, params, url } = action;
const defaultOptions = {
headers: {
Authorization: token ? `Token ${token}` : '',
}
};
const options = {
...defaultOptions,
...params
};
try {
const response = await axios[method](url, options);
dispatch(onSuccess(response.data));
} catch (error) {
dispatch(onError(error.data));
}
return next(action);
};
Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.
export default () => {
axios.interceptors.request.use(function (requestConfig) {
if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
const token = localStorage.token;
requestConfig.headers['Authorization'] = `Bearer ${token}`;
}
return requestConfig;
}, function (error) {
return Promise.reject(error);
});
}
Try to make new instance like i did below
var common_axios = axios.create({
baseURL: 'https://sample.com'
});
// Set default headers to common_axios ( as Instance )
common_axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Check your Header
console.log(common_axios.defaults.headers);
How to Use it
common_axios.get(url).......
common_axios.post(url).......
export const authHandler = (config) => {
const authRegex = /^\/apiregex/;
if (!authRegex.test(config.url)) {
return store.fetchToken().then((token) => {
Object.assign(config.headers.common, { Authorization: `Bearer ${token}` });
return Promise.resolve(config);
});
}
return Promise.resolve(config);
};
axios.interceptors.request.use(authHandler);
Ran into some gotchas when trying to implement something similar and based on these answers this is what I came up with. The problems I was experiencing were:
If using axios for the request to get a token in your store, you need to detect the path before adding the header. If you don't, it will try to add the header to that call as well and get into a circular path issue. The inverse of adding regex to detect the other calls would also work
If the store is returning a promise, you need to return the call to the store to resolve the promise in the authHandler function. Async/Await functionality would make this easier/more obvious
If the call for the auth token fails or is the call to get the token, you still want to resolve a promise with the config

How to use basic auth with axios nuxt module

I am currently struggling with Nuxt's Axios module: https://axios.nuxtjs.org/.
I would like to get some data from a specific endpoint where I have to use Basic Authentication.
Normally, with Axios, I would do something like:
await axios.get(
'http://endpoint',
{},
{
withCredentials: true,
auth: {
username: 'userame',
password: 'pw'
}
}
)
Unfortunately, with Nuxt's Axios module, it seems it is not that easy...
I tried something like:
const data = await this.$axios.$get(
'http://endpoint',
{},
{
credentials: true,
auth: {
username: 'user',
password: 'pw'
}
}
)
But that leaves me with a 401 Unauthorized...
What am I missing here?
The second argument to axios.get() (and $axios.$get()) is the Axios config, but you've passed it as the third argument (which is effectively ignored). The API likely omits the data argument from axios.get() because data doesn't apply in this context.
The solution is to replace the 2nd argument with your config:
const data = await this.$axios.$get(
'http://endpoint',
// {}, // <-- Remove this! 2nd argument is for config
{
credentials: true,
auth: {
username: 'user',
password: 'pw'
}
}
)

graphql query with fetch producing 400 bad request

I am trying to write a basic graphql query with fetch that works when using apollo client. But it does not work with node-fetch.
The type definitions look like this:
type Query {
findLeadStat(print: PrintInput!): LeadStatWithPrint
}
input PrintInput {
printa: String!
service: String
}
type LeadStatWithPrint {
answered: Int!
printa: String!
service: String
}
This is the node-fetch query:
const fetch = require('node-fetch');
( async () => {
const uri = `http://localhost:3000/graphql/v1`;
const query = `
query findLeadStat(print: PrintInput!) {
findLeadStat(print: $print){
answered
printa
service
}
}
`;
// I also tried add a query: key inside data object
const data = {
print: {
printa: "62f69234a7901e3659bf67ea2f1a758d",
service: "abc"
}
}
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({query, data})
});
console.log('and the resp: ', response);
})()
It gives me:
url: 'http://localhost:3000/graphql/v1',
status: 400,
statusText: 'Bad Request',
It works in Apollo GraphQL Client. Why doesn't it work with fetch?
So when I was using async await with node-fetch, the response was pretty much useless. It was just telling me there was a 400 bad request error and then give me this long object of properties, none of them containing the actual error message.
But when I changed the fetch call to this:
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables}) // same as query: query, variables: variables
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error('ERROR: ', err));
There two lines right here:
.then(res => res.json())
.then(json => console.log(json))
made it clear what the issue was:
{
errors: [
{
message: 'Syntax Error: Expected $, found Name "fingeprint"',
locations: [Array],
extensions: [Object]
}
]
}
It appears node-fetch has two async events occurring and so await had to be used twice:
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables}) // same as query: query, variables: variables
})
console.log('and the resp: ', await response.json());
A 400 status indicates your query was invalid or malformed. When this happens, the response will include a JSON body with an errors array that can be inspected to determine what exactly went wrong.
In this particular case, the issue is that your query includes a non-nullable variable ($print) but this variable was not provided along with the query.
When making a GraphQL request, the request body should be a JSON object with a query property and two other optional properties -- variables and operationName. operationName is used to identify which operation to execute if multiple operations were included in the provided document (the query property). Any non-nullable variables defined in the executed operation must be included as properties under the variables property, which is also an object. Nullable properties may be omitted altogether.
In other words, you need to change the data property in your request to variables in order for the server to recognize that the variable was provided with the request.

Redirect (react router dom) giving Expected an assignment or function call and instead saw an expression no-unused-expressions

I'm new Reactjs, I'm using fetch for api call. I want to redirect the page with api data on some other page, for that I'm using below code
import React, { Component } from 'react';
import OwlCarousel from 'react-owl-carousel';
import 'owl.carousel/dist/assets/owl.carousel.css';
import 'owl.carousel/dist/assets/owl.theme.default.css';
import { Link,Redirect } from 'react-router-dom';
fetchCatList(){
let catID = "5c2f74e8a4d846591b2b1a41";
// fetch("http://sfsdfsdfsdf/api/listing",{
// method: 'POST',
// body: JSON.stringify({
// category_id: catID,
// }),
// headers:{
// 'Content-Type':'application/json',
// },
// })
// .then(res => res.json())
// .then(json => this.setState({catlist:json.data}));
fetch("http://sdfsdfsdf/api/listing", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
category_id: catID,
})
})
.then(function(res){ return res.json(); })
.then(function(response){
//do something awesome that makes the world a better place
console.log(response);
<Redirect to={{
pathname: '/listing_page',
state: { listData: response }
}}/>
});
}
I'm using Redirect from react-router-dom but getting below error after calling api
Expected an assignment or function call and instead saw an expression
no-unused-expressions
Search for the keywords to learn more about each error.
To solve your problem you need to to use redirect with return.
render () {
if(this.state.toListing) {
return <Redirect push to="/listing_page" />
}
return (
...
)
}
Here they have mentioned that this is an eslint error and not an error from the router.
refer : https://github.com/ReactTraining/react-router/issues/4718

Calling graphQL server mutation to axios url

I am currently using GraphQL Server and axios for client side.
I would like to know how to call this graphQL to my axios
mutation {
createUser(email: "hello#gmail.com") {
email
}
}
How can I call it like this?
const res = await axios.get('http://localhost:5000/public?query={users{email}');
You need to use post method to send your query/mutation to the GraphQL server:
axios({
// Of course the url should be where your actual GraphQL server is.
url: 'http://localhost:5000/graphql',
method: 'post',
data: {
query: `
mutation createUser($email: email){
createUser(email: $email) {
email
}
}`,
variables: {
email: "hello#gmail.com"
}
}
}).then((result) => {
console.log(result.data)
});

Categories