Making request parameter optional in axios get request - javascript

I have below axios request.
import axios from 'axios';
axios.get('/user', {
params: {
ID
Name
}
})
.then(function (response) {
console.log(response);
})
I want all the request parameter should be optional. if user send ID then it should give ID, if user enter ID and Name it should consider both. If user enters none it should display all the record.
I dont know how to handle this in react.

think u are looking for something like below:
params: {
...(ID && {
ID: ID
}) // conditional spread operator
}

You would evaluate the params in a variable based on a condition before giving them to axios:
const parameters = condition ? {ID: id, Name: name} : {};
axios.get('/user', {
params: parameters
})
.then(function (response) {
console.log(response);
})

Related

my error object is undefined when i`m using rtk query with try/catch

first of all i want to apologize for my title. I just dont know how to describe my problem.
I am trying to get a bad response from my server and when I try to display that my object is undefined
I have a base query methods here:
export const accountSlice = apiSlice.injectEndpoints({
endpoints: builder => ({
login: builder.mutation({
query: credentials => ({
url: 'account/login',
method: 'POST',
body: { ...credentials },
})
}),
register: builder.mutation({
query: credentials => ({
url: 'account/register',
method: 'POST',
body: { ...credentials },
})
})
})
})
My handle submit on register page ->
const [register, { isLoading, isError }] = useRegisterMutation();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const result = await register({ name, nickName, email, password }).unwrap();
setRegisterResponse(result);
} catch (error) {
setRegisterResponse(error);
}
}
And my logic to show it. When i use console.log(registerResponse) it returnes two logs in console - first object is empty, second object with properties ->
{
isError &&
<h2>
Ooops.. something went wrong:
{
console.log(registerRespnse)
}
</h2>
}
Error in google console
You shouldn't need to call a setRegisterResponse state setter, because that response will just be available for you:
// see data and error here
const [register, { isLoading, isError, data, error }] = useRegisterMutation();
As why it logs undefined once: first the query finishes with an error (which will rerender the component and already fill error I showed above and set isError) and then the Promise resolves and your custom code sets your response local state, which causes a second rerender (and only on the second render, response is set)

how to write one GET api call using axios instance with and without params in React JS

I am new to React JS and Axios. I want to understand the best way of creating a GET instance using Axios that works with and without params. I am have developed a sample REST API call from React using axios.create({}) as below and it works fine.
import axios from 'axios';
const instance = axios.create({
baseURL: 'example.com'
});
export default {
getAllData: (url) =>
instance({
'method': 'GET',
'url': url
})
}
My requirement is to create axios GET instance that works with and without params and I could achieve it like below by creating 2 different functions:
export default {
getAllData: (url) =>
instance({
'method': 'GET',
'url': url
}),
getUser: (url, userId) =>
instance({
'method': 'GET',
'url': url,
'params' : userId
})
}
Is there any way to create one GET function that works with and without params using Axios in React JS?
You can do something like this:
getUser: (url, userId) =>
instance({
'method': 'GET',
'url': url,
...(userId && {'params' : userId})
})
If userId exists, it will append the {'params': userId} object to the current one.
You don't have to create 2 different methods. If you don't pass the userId parameter, it will be null and won't be passed to the API call.
You can use this code:
import axios from 'axios';
// Set Global default
axios.defaults.baseURL = 'example.com';
const getData = (url, userId) => axios(url, userId);
export default getData;
You can call with userId:
getData('/user', userId);
Or without:
getData('/user');
This is how you can do it:
export default {
getUser: (url, userId) =>
instance.get(url, {
...(userId && {'params' : userId})
})
}
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})

Extracting token from the URL and sending a post request using Axios - Vue js

I have been trying to extract a token from say http://test.com/confirm?token=MMsndiwhjidh... and then send a post request to another server.
I have tried this:
export default {
data() {
return {
confirmation : false,
somethingWrong: false
}
},
created: function() {
axios.post('/confirm', null, {
method: 'post',
params: {
token:this.$route.query.token
}
})
.then(function(res) {
console.log(res)
this.confirmation = true
})
.catch(function(error) {
console.log(error)
this.somethingWrong = true
})
}
}
I got the following errors:
I think I am not able to extract the token properly.
The reason is you're using declarative functions instead of arrow functions in your then / catch blocks. The this don't refer to the same thing (here, this is not your Vue component).
Try like this:
.then((res) => {
console.log(res)
this.confirmation = true
})
I won't try to explain the difference myself as there are plenty of articles on the web about it. Here's one

How to pass a query param in post call in Reactjs

I am new to reactjs.I am doing a post call but not sure, how to pass a boolean value in url as a query param in reactjs. For eg: http://www.abx.com?example=true. How do I pass this example in post api call.
Endpoint: API_SAMPLE: "/sample",
post call:
postCall() {
const config = {
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
product: {
body
},
};
return http
.post(this.API.API_SAMPLE, data, config)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
i want to add a boolean value in my query param, how will i do that
You can use template literals to pass the variable to your URL.
const example = true;
const url = `http://abx.com/sample?example=${example}`
or use it this way:
return http.post(`${this.API.API_SAMPLE}?example=${example}`, data, config) {...}
wether you are using POST or GET you will have to modify the URL.
You can do this "dynamically" or you can use something like URLSearchParams:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var URL = "http://example.com/search";
var searchParams = new URLSearchParams(URL);
searchParams.append("example", "true");
searchParams.toString() // "http://example.com/search?example=true";
Just make sure you support the correct browsers:
https://caniuse.com/#search=urlsearchparams

Passing parameters in get query to vue js?

I do the filtering, when I click on the apply filter, the query in the API flies away
php-developer, says that the request should be get, not post
how to pass parameters to the get query?
example for my post request
export const filterDate = (options) => {
console.log(options)
return axios.post(url, options).then(({ data }) => {
if (data.errors) throw new Error(JSON.stringify(data.errors));
return data;
})
};
but if I just replace the post on the get parameters are not transferred
If you want to pass parameters in get request, pass an object with "params" property, as follow:
axios.get('/user', {
params: {
ID: 12345
}
});
in options you specify a param object:
params: {
k: val
},
or by building an UrlSearchParam object:
const params = new URLSearchParams();
params.append('k', 'val');
axios.get(url, params);

Categories

Resources