How to return const from react axios function in another file? [duplicate] - reactjs

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a file with form to call a submit function in another file.
And I would like to retrieve the response of the request to use it in file 1.
How can I do that ?
First file form.js
handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
newAppartement(newAppartementTableau);
const messageRequest = ??;
Second file data.js
export function newAppartement(newAppartementTableau) {
axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}

You are not returning anything in your function, you're just making an axios call. To solve this add this :
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}
in your first file
newAppartement(newAppartementTableau).then(res => console.log(res.data).catch(e => console.error(e));

You need to wait for the function to finish using await async:
async handleSubmit(event, user,props) {
event.preventDefault();
const nomAppartement = event.target.nomAppartement.value;
const superficieAppartement = event.target.superficieAppartement.value;
const newAppartementTableau = {
nom: nomAppartement,
};
const response = await newAppartement(newAppartementTableau);
and in second file you can return a promise like this:
export function newAppartement(newAppartementTableau) {
return axios({
method: "post",
url: urlAxiosAppartement,
timeout: 1000 * 5, // Wait for 5 seconds
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "****"
},
data: {
fields: {
nom: newAppartementTableau.nom
}
}
})
.then((response) => {
return response;
})
.catch((err) => {
return err;
});
}

Related

converting custom react function to async

I made this custom hook.
import axios from "axios";
import Cookies from "js-cookie";
import React from "react";
const useGetConferList= () => {
let token = JSON.parse(localStorage.getItem("AuthToken"));
const Idperson = JSON.parse(Cookies.get("user")).IdPerson;
const [response, setResponse] = React.useState();
const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
.then((r) => {
setResponse(r.data.Data);
})
.catch(() => alert("NetworkError"));
};
return { fetchConfer, response };
};
export default useGetConferList;
as you can see I export the fetchConfer function. but I want to make it async. for example, calling the function and then doing something else like this:
fetchConfer(Date, Time, Id).then((r) => {
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
});
as you can see in non async situation, I can't use then.
You can try this
const fetchConfer = async (datePrensence, idInsurance, timePrensence) => {
try {
const response = await axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
setResponse(response.data.Data);
// need to return data
return response.data.Data
} catch(error) {
alert("NetworkError")
}
};
use the function in another async function
const someAsyncFunc = async () => {
// try catch
const r = fetchConfer(Date, Time, Id)
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
...
or use it how you are currently using it
Hope it helps

How to show data using react

you are currently using react to replicate Spotify.
You are currently developing a search function and have successfully received a response.
I want to show this on the screen.
How do I solve this? Please help me.
const onClick = () => {
const inputSearchData = sessionStorage.getItem('inputData');
const inputTypeData = sessionStorage.getItem('inputType');
// console.log(inputTypeData)
axios({
headers: {
"Authorization": `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
},
method: 'GET',
url: 'https://api.spotify.com/v1/search',
params: {
q: inputSearchData,
type: inputTypeData,
},
}).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
when you get your response from your axios request you need to store it inside react state.
access this inside the return statement of the component.
That will be something like that :
const SomeComponent = () => {
const [response, setResponse] = useState();
const onClick = async () => {
const inputSearchData = sessionStorage.getItem("inputData");
const inputTypeData = sessionStorage.getItem("inputType");
await axios({
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET",
url: "https://api.spotify.com/v1/search",
params: {
q: inputSearchData,
type: inputTypeData
}
})
.then((res) => {
setResponse(res);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
{/* Access your response state over here */}
{/* That will be something like that : */}
{response.map((item, index) => {
<div key={index}>
{item.somethingFromYourData}
</div>
})}
</div>
)
};

How to create a Spotify playlist using react?

I am trying to create a playlist on localhost and then have the list I created to be saved to Spotify. Can someone help why Save to Spotify button might not be working? Everything else seems fine, I have doubts about the fetching part I used but can't figure out what the issue might be.
Screenshot of the page:
And there is the Spotify.js code:
import { SearchBar } from '../components/SearchBar/SearchBar';
const clientId = 'I've put my client id';
const redirectUri = 'http://localhost:3000/callback/';
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
let expiresIn = Number(expiresInMatch[1]);
//This clears the parameters, allowing to grab new access token then it expires
window.setTimeout(() => (accessToken = ''), expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((response) => {
return response.json();
})
.then((jsonResponse) => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map((track) => ({
id: track.id,
name: track.name,
artists: track.artists[0].name,
album: track.album.name,
uri: track.uri,
}));
});
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userId;
return fetch(`https://api.spotify.com/v1/me`, { headers: headers })
.then((response) => response.json())
.then((jsonResponse) => (userId = jsonResponse.id))
.then((userId) => {
return fetch(`/v1/users/${userId}/playlists`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ name: name }),
})
.then((response) => response.json())
.then((jsonResponse) => {
const playlistId = jsonResponse.id;
return fetch(`/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris }),
});
});
});
},
};
export default Spotify;
Here is the screenshot of Element > Console:
I had an fetch error, updated as below and working now.
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
let expiresIn = Number(expiresInMatch[1]);
//This clears the parameters, allowing to grab new access token then it expires
window.setTimeout(() => (accessToken = ''), expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((response) => {
return response.json();
})
.then((jsonResponse) => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map((track) => ({
id: track.id,
name: track.name,
artists: track.artists[0].name,
album: track.album.name,
uri: track.uri,
}));
});
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userID;
return fetch('https://api.spotify.com/v1/me', { headers: headers })
.then((response) => response.json())
.then((jsonResponse) => {
userID = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userID}/playlists`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ name: name }),
})
.then((response) => response.json())
.then((jsonResponse) => {
const playlistID = jsonResponse.id;
return fetch(
`https://api.spotify.com/v1/users/${userID}/playlists/${playlistID}/tracks`,
{
method: 'POST',
headers: headers,
body: JSON.stringify({ uris: trackUris }),
}
);
});
});
}, // end of savePlaylist method
}; // end of Spotify object
export default Spotify;

How to use post method in react native?

constructor(props) {
super(props);
this.state = {text: this.props.navigation.state.params.text,
name:this.props.navigation.state.params.name};
}
manage = () => {
Alert.alert('done')
Actions.reset('mainScreen');
fetch("http://ip/api/confirm", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.props.navigation.state.params.name,
text:this.props.navigation.state.params.text
})
})
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
i want to do this
when i press in button go to manage function
and post the text and the name to my api i dont know how can i pass them
its give me this error :
network request failed
any help please
I recommend you to use axios to make network requests.
Installing:
npm i -S axios
Performing a POST request:
import axios from 'axios';
axios({
url: 'http://ip/api/confirm',
method: 'post',
data: {
name: this.props.navigation.state.params.name,
text: this.props.navigation.state.params.text,
},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
var resp = await manage(this.props.session.userId,this.props.session.ApiKey,"hi","hello");
if (resp.status == 200){
var respBody = await resp.json();
console.log('Fetch Todo response '+respBody);
}
API in separate file
export async function manage(userId,ApiKey,query,query1) {
var url ="http://www.example.com/getdata";
const params = {
search:query,
searches:query1
};
var formBody = [];
for (const property in params) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(params[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
const requestOptions = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'application/json'
},
'body': formBody
};
requestOptions.headers["userid"] = userId
requestOptions.headers["apikey"] = ApiKey
try {
var resp = await fetch(url, requestOptions);
return resp;
}
catch (err) {
console.log("Request Failed: " + err);
return err;
}
}

Return data from method in object

I have been trying to figure this one out and I'm not getting how to return the data to another method and call it so that I don't have to statically add the data into my request. I keep getting undefined data on my B2C method when I run it for the data returned from this.O_Auth. Any clues?
let obj = {
O_Auth(key, secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
request(
{
uri: "https://randomurl",
method: 'GET',
headers: {
"Authorization": auth
}
},
(err, res, body) => {
if (err) {
return err;
} else {
// console.log(body);
let response = JSON.parse(body);
let res = JSON.stringify(response.access_token)
return res;
}
}
);
},
B2C(params) {
console.log("Random " + this.O_Auth('first', 'second'));
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + this.O_Auth('first', 'second'),
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}
}
Ended up figuring out the asynchronous nature of JavaScript meant I was requesting data that was being evaluated later so I used a promise to get the data and output it first before using it in a subsequent promise that outputs the body. Changed the first request to request promise (rp) that returns the options that will be needed for that promise in the second method.
let obj = {
O_Auth(Key, Secret) {
const key = Key;
const secret = Secret;
const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");
let options = {
uri: "https://randomurl",
headers: {
"Authorization": auth
},
json: true
};
return rp(options)
},
B2C(param1, param2, param3...) {
this.O_Auth('first', 'second'))then(response =>{
let token = response.access_token;
let options = {
method: 'POST',
uri: 'https://randomurl',
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
},
body: {
//values
},
json: true
};
rp(options)
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err);
});
}).catch(error => console.log(error));
}
}

Resources