can not read/write data in function - vue.js

Hi i am use vue and axios for upload file
Does not recognize the list inside in onUploadProgress
code
data: ()=>({
list: [
{ id:0, icon: 'image', iconClass: 'blue white--text', title: 'Vacation itinerary', file:"asasf.png", progress:100 },
selectedFile: null
]
}),
methods:{
async startUpload(){
let formData = await new FormData();
await formData.append('file', this.selectedFile);
this.selectedFile=null
let config = {
onUploadProgress: function(progressEvent){
console.log(this.list) //is null
this.list[id].progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
}
};
this.$axios.$post('/upload/insert', formData, config)
.then(response => {
this.list[id].progress=100
this.list[id].file=response.data.path
})
.catch(error => {
console.log(error)
})
}
}
console.log(this.list) in lone 16 is null

Just change onUploadProgress function to arrow function, otherwise this will be related to the context of onUploadProgress instead of the component.
async startUpload(){
let formData = await new FormData();
await formData.append('file', this.selectedFile);
this.selectedFile=null
let config = {
onUploadProgress: (progressEvent) => {
console.log(this.list) //is null
this.list[id].progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
}
};
this.$axios.$post('/upload/insert', formData, config)
.then(response => {
this.list[id].progress=100
this.list[id].file=response.data.path
})
.catch(error => {
console.log(error)
})
}

Related

how to fetch data from Api folder in next.js

I"m facing this problem, I store my submitted data in api folder from a page and i successfully can store it and when i console.log it I can see the data but the problem is when I try fetch it to a page where I want show all this data then I didn't get any result, it's shows empty object:
this is the page from where I submitted data to api folder/page
const handleSubmitAllData = async (e) => {
e.preventDefault();
const allData = {
addStory,
selectedVideoUrl,
};
console.log("AllNftData:", allData);
try {
const { data } = await axios({
url: "/api/uploadNftData",
method: "POST",
data: allData,
});
console.log("response Data", data);
} catch (error) {
console.log("Error", error);
}
router.push("/template/marketplace");
};
this is the api page where store data, when console.log the data i see it that's means it's working
this is code of api page
const { log } = console;
export default function teamAdd(req, res) {
if (req.method === "POST") {
const nftData = req.body;
log("Req payload", nftData);
res.json(nftData);
}
return res.status(500).json({
msg: "this needs to be post request",
});
}
and this is page where I try to fetch this store data from api. this is code , it's not working. I try so many time but it's always comes out with not data
function page() {
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(false);
const [comments, setComments] = useState([]);
const fetchComments = async () => {
const response = await fetch("/api/uploadNftData");
const data = await response.json();
setComments(data);
console.log(data);
};
useEffect(() => {
setLoading(true);
fetch("/api/uploadNftData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
setData(data);
setLoading(false);
})
.catch((error) => {});
}, []);
if (isLoading) return <p>Loading...</p>;
if (!data) return <p>No profile data</p>;
return (
<>
<Main>
<Templatepage>
<TemplateHeader />
<Herosec>
marketplace
<Box
sx={{
background: "#000",
height: "200px",
width: "200px",
margin: "80px",
}}
>
<h1 style={{ color: "#fff" }}>{data.addStory}</h1>
<p style={{ color: "#fff" }}>{data.selectedVideoUrl}</p>
</Box>
</Herosec>
</Templatepage>
</Main>
</>
);
}
What happens if you try to update the dependency array of the useEffect with data
useEffect(() => {
setLoading(true);
fetch("/api/uploadNftData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
setData(data);
setLoading(false);
})
.catch((error) => {});
}, [data]);
And I would change the default state of
const [data, setData] = useState(null);
to something more reliable like some custom interface or type.
You can try to verify if data is null in useEffect and then do the request.
It should look something like this:
useEffect(() => {
if(data === null){
setLoading(true);
fetch("/api/uploadNftData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
setData(data);
setLoading(false);
})
.catch((error) => {});
}
}, [data]);

Sending a PUT request with Spotify's WebAPI returns a 401 error

What I want to do
I want to change the playlist image using Spotify's API.
API reference:https://developer.spotify.com/documentation/web-api/reference/#/operations/upload-custom-playlist-cover
Problem
API request returns 401 error.
Access token is fine.
Other requests using the same axios instance (spotify_api) are fine.
Even if the access token is invalid, the process of reissuing and repeating the previous request runs.
My Code
home.vue
import spotify_api from "../../util/spotify_api";
import fivetune_api from "../../util/fivetune_api";
let fi_user_id = "";
let sp_user_id = "";
let access_token = "";
export default {
data() {
return {
playlists: [],
tracks: [],
track: {
no: 1,
artist: "",
artist_url: "",
album_url: "",
track_name: "",
track_image_url: "",
track_url: "",
},
};
},
name: "Home-1",
props: {
msg: String,
},
async created() {
fi_user_id = this.$cookies.get("fi_user_id");
access_token = this.$cookies.get("access_token");
await fivetune_api.get("/api/user/" + fi_user_id).then((res) => {
sp_user_id = res.data.sp_user_id;
});
fivetune_api.get("/api/playlist/home").then(async (res) => {
this.playlists = res.data;
for (let i = 0; i < this.playlists.length; i++) {
this.tracks = [];
await Promise.all([
spotify_api.get("/users/" + this.playlists[i].sp_creator_user_id),
fivetune_api.get("/api/download/" + this.playlists[i].fi_playlist_id),
])
.then((res2) => {
this.playlists[i].creator_name = res2[0].data.display_name;
this.playlists[i].download_count = res2[1].data[0].download_count;
})
.catch((err) => {
console.log(err);
console.log(access_token);
// access_token = refreshToken(err);
});
for (let j = 0; j < this.playlists[i].track_ids.length; j++) {
await spotify_api
.get("/tracks/" + this.playlists[i].track_ids[j].sp_track_id)
.then((res_track) => {
this.track = {
no: j + 1,
track_id: res_track.data.id,
artist: res_track.data.artists[0].name,
artist_url: res_track.data.artists[0].external_urls.spotify,
album_url: res_track.data.album.external_urls.spotify,
track_name: res_track.data.name,
track_image_url: res_track.data.album.images[0].url,
track_url: res_track.data.external_urls.spotify,
};
this.tracks.push(this.track);
})
.catch((err) => {
console.log(err);
// access_token = refreshToken(err);
});
}
this.playlists[i].tracks = this.tracks;
this.playlists[i].playlist_image =
process.env.VUE_APP_HOST +
"/images/playlist/" +
this.playlists[i].fi_playlist_id +
".jpeg";
}
});
},
methods: {
download: async function (index) {
const track_1 = document.getElementById(
`playlist-${index}-track-0-id`
).value;
const track_2 = document.getElementById(
`playlist-${index}-track-1-id`
).value;
const track_3 = document.getElementById(
`playlist-${index}-track-2-id`
).value;
const track_4 = document.getElementById(
`playlist-${index}-track-3-id`
).value;
const track_5 = document.getElementById(
`playlist-${index}-track-4-id`
).value;
const fi_playlist_id = document.getElementById(
`playlist-${index}-id`
).value;
const playlist_name = document.getElementById(
`playlist-${index}-playlist-name`
).innerHTML;
///////////////////////////////////////////////////////////////////////////////////////////////////
////// this //////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
spotify_api
.post("/users/" + sp_user_id + "/playlists", {
name: playlist_name,
description: "",
public: false,
})
.then(async (res) => {
const created_playlist_id = res.data.id;
spotify_api
.put("/playlists/" + created_playlist_id + "/images", {
data: this.playlists[index].img_base64
})
.then(() => {})
.catch((err) => {
console.log(err);
});
///////////////////////////////////////////////////////////////////////////////////////////////////
////// end //////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
await Promise.all([
spotify_api.post("/playlists/" + created_playlist_id + "/tracks", {
uris: [
"spotify:track:" + track_1,
"spotify:track:" + track_2,
"spotify:track:" + track_3,
"spotify:track:" + track_4,
"spotify:track:" + track_5,
],
}),
])
.then(() => {
fivetune_api
.post("/api/download", {
fi_user_id: fi_user_id,
fi_playlist_id: fi_playlist_id,
})
.then(() => {
this.playlists[index].download_count += 1;
this.$swal.fire({
title: "ダウンロード完了",
html: "Spotifyのプレイリストに追加されました。",
confirmButtonColor: "#8db30f",
});
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
this.$swal.fire({
title: "ダウンロード失敗",
confirmButtonColor: "#8db30f",
});
});
});
},
},
};
spotify_api.js(
An instance of axios is created)
import axios from 'axios';
const spotify_api = axios.create({
baseURL: 'https://api.spotify.com/v1',
withCredentials: false,
})
let refresh_token_promise;
const getRefreshToken = () => {
return new Promise((resolve) => {
console.log(300)
axios.get('/api/refresh').then((res) => {
const access_token = res.data
return resolve(access_token)
}).catch((err) => {
console.log('err 2')
console.log(err)
})
})
}
spotify_api.interceptors.request.use(req => {
req.headers = {
authorization: `Bearer ${localStorage.getItem('access_token')}`,
"Content-Type": "application/json",
}
return req
})
spotify_api.interceptors.response.use((res) => {
return res
}, (err) => {
if (err.config && err.response && err.response.status === 401 && !err.config._retry) {
console.log(100)
if (!refresh_token_promise) {
err.config._retry = true;
refresh_token_promise = getRefreshToken().then((token) => {
refresh_token_promise = null;
console.log(token)
localStorage.setItem('access_token', token)
return token
}).catch((err) => {
console.log('err')
console.log(err)
})
}
console.log(200)
return refresh_token_promise.then((access_token) => {
const config = err.config;
config.headers = {
authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
}
return axios.request(config)
}).catch((err) => {
console.log(err)
})
}
return Promise.reject(err)
})
export default spotify_api
What I tried
I tried various names of the body requesting the image
( data、image、postData )
I tried setting Content-Type to image/jpeg
I wrote it directly without using axios instant.
await axios
.put(
"https://api.spotify.com/v1/playlists/" +
created_playlist_id +
"/images",
{
data: this.playlists[index].img_base64,
headers: {
authorization: `Bearer ${localStorage.getItem(
"access_token"
)}`,
"Content-Type": "application/json",
},
}
)
.then((res_image) => {
console.log("res_image");
console.log(res_image);
})
.catch((err) => {
console.log("err");
console.log(err);
});
Environment
FrontEnd
Vue.js3
BackEnd
Node.js

How to upload a file in react-native iOS?

While trying to upload a file I ran into an issue on iOS, the code works fine on android. After a bit of googling, I found that it is a known issue in react-native iOS and has a bug report submitted. This is the issue. I want to know if there is any other way to upload files on iOS. Below is the snippet of code I'm using. Please let me know if there is something that can be done.
const resp = await fetch(uploadUrl, {
method: 'POST',
headers: {
'content-type': 'multipart/form-data',
},
body: file, // file is File type
});
You can something like below code snippet
function uploadProfileImage(image, token) {
const url = ServiceUrls.UPLOAD_PROFILE_IMAGE
return uploadResourceWithPost({
url,
authToken: token,
formData: createFormData(image),
})
}
const createFormData = (data) => {
const form = new FormData()
form.append('file', {
uri: Platform.OS === 'android' ? data.uri : data.uri.replace('file://', ''),
type: 'image/jpeg',
name: 'image.jpg',
})
return form
}
const uploadResourceWithPost = ({ url, authToken, formData }) => {
return handleResponse(axios.post(url, formData, defaultUploadOptions(authToken)))
}
const defaultUploadOptions = (authToken) => ({
timeout,
headers: {
'X-Auth-Token': authToken,
'Content-Type': 'multipart/form-data',
},
})
const handleResponse = (responsePromise) => {
return NetInfo.fetch().then((state) => {
if (state.isConnected) {
return responsePromise
.then((response) => {
return ResponseService.parseSuccess(response)
})
.catch((error) => {
return ResponseService.parseError(error)
})
}
return {
ok: false,
message: 'Check your network connection and try again.',
status: 408,
}
})
}
const parseSuccess = ({ data, headers }) => ({ ...data, headers, ok: true })
const parseError = ({ response }) => {
let message = 'Check your network connection and try again.'
let status = 408
if (response && response.data) {
const { data } = response
message = data.message
status = data.code
}
return { status, message }
}

Await is only allowed within async functions error react native

I am new to react native and trying to save user obejct in application storage using await AsyncStorage.setItem('user', res[1].data); However I am getting error as
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
const {navigate} = this.props.navigation;
const data = {
email: this.state.userName,
password: this.state.password
};
fetch(`${DOMAIN_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then((response) => {
const statusCode = response.status.toString();
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((res) => {
if (res[0] == 200) {
await AsyncStorage.setItem('user', res[1].data);
navigate('Home');
}else{
Alert.alert(
res[1].message
);
}
})
.catch((error) => {
console.error(error);
});
}
else {
Alert.alert(
"No Internet!",
"Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
[
{
text: "OK",
onPress: () => { }
}
]
);
};
})
};
I have made the handleLogin async but it doesn't solve the error. What is the correct way to store user obejct?
It is recommended that you use react-native-easy-app , through which you can access any data in AsyncStorage synchronously.
Sample_Hooks
StorageController
navigateToHome = async (user) => {
const { navigate } = this.props.navigation;
await AsyncStorage.setItem('user', user);
navigate('Home');
}
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
const data = {
email: this.state.userName,
password: this.state.password
};
fetch(`${DOMAIN_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then((response) => {
const statusCode = response.status.toString();
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((res) => {
if (res[0] == 200) {
navigateToHome(res[1].data);
}else{
Alert.alert(
res[1].message
);
}
})
.catch((error) => {
console.error(error);
});
}
else {
Alert.alert(
"No Internet!",
"Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
[
{
text: "OK",
onPress: () => { }
}
]
);
};
})
};

React Native: setState doesn't work when calling try-catch function

I tried to call APP with this code imported from another file and it worked fine:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
let formData = new FormData();
formData.append('userId', '1'); // < this is what I want to change
formData.append('key', '***'); //my key
export function getScoreFromAPI () {
return fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
}
but now I want to change my userId from 1 to an constante from Asyncstorage, so I decide to change my code to this:
constructor(props) {
super(props)
this.state = { infos: [], userId: '' }
}
componentWillMount() {
this.getScoreFromAPI().then(data => {
this.setState({ infos: data })
});
console.log(this.state.infos);
AsyncStorage.getItem(USERID_STORED)
.then((data) => {
if (data) {
this.setState({userId:data})
}
});
}
async getScoreFromAPI() {
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
try {
let response = await fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
let res = await response.json();
} catch(error) {
console.warn("errors are " + error);
}
};
with a try-catch function but when I call getScoreFromAPI() in ComponentWillMount() I can't setState with received data, I still have an empty array in info:[]
my questions:
how can I replace '1' in userId by a value in asyncstorage in the first file ?
if it isn't possible, what I have do to setState info: [] with my data reveived
I've simplified your code into a promise chain in which calling getScoreFromAPI will execute after getting the userId from AsyncStorage, then storing the response into the infos state, while returning null if there was an error, and logging the error to the console. The data was not previously returned from getScoreFromAPI, so the value would always become null. I have not tested this code, but this should give you a good base to work from:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
export default class Test {
constructor() {
this.state = {
infos: null,
userId: ''
};
}
componentDidMount() {
AsyncStorage.getItem(this.state.userId)
.then(userID => {
this.setState({ userId: userID || '' });
})
.then(() => {
return this.getScoreFromAPI();
})
.then(data => {
this.setState({ infos: data });
})
.catch(console.error);
}
getScoreFromAPI = () => {
const formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(response => {
// use response data here
return response.json();
})
.catch(e => {
console.error(e);
return null;
});
};
}
You're doing your API call before fetching your value from AsyncStorage (I know this is async but it's not very readable if you do it that way).
getScoreFromAPI doesn't return anything, that's why your setState isn't working.
You don't need to use try and catch here, promises have their own error handling mechanism (the .catch() method).
I think callbacks are more readable and lead to less bugs than using .then() in code.
This is how I would do it:
constructor(props)
{
super(props);
this.state = { infos: [], userId: '' };
this.onSuccess = this.onSuccess.bind(this);
this.onFailure = this.onFailure.bind(this);
}
componentWillMount()
{
// Get userID from local storage, then call your API
AsyncStorage.getItem(YOUR_KEY)
.then(userID=> {
if (userID)
{
this.setState({ userId : userID }, () => {
this.getScoreFromAPI(this.onSuccess, this.onFailure);
});
}
});
}
onSuccess(data)
{
this.setState({
infos : data
});
}
onFailure(err)
{
console.warn('Error ' + err);
}
getScoreFromAPI(onSuccess, onFailure)
{
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //your key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(res => res.json())
.then(json => {
onSuccess(json);
})
.catch(err => {
onFailure(err);
});
}
It's finally done. I tried this and it worked. Thank you to all of you
this is what I have done:
...
const USERID_STORED = "userid_stored";
const GSM_STORED = "gsm_stored";
...
class ScoreList extends React.Component {
constructor(props) {
super(props)
this.state = { infos: [], userId: '', gsmStored: '', }
}
componentWillMount() {
AsyncStorage.getItem(USERID_STORED)
.then(userId => {
this.setState({ userId: userId});
this.getScoreFromAPI(this.state.userId).then(data => {
this.setState({ infos: data });
});
});
AsyncStorage.getItem(GSM_STORED)
.then(gsmStore => {
this.setState({ gsmStored: gsmStore});
});
}
getScoreFromAPI (userId) {
let formData = new FormData();
formData.append('userId', userId);
formData.append('key', '***');
return fetch('https://***',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
};