ReactJS: post request with data through fetch - reactjs

In my app component, I have state features that contains an array(1500) of arrays(9). I want to send the state (or large array) to my backend so I can run my model and return labels with the following function:
const getLabels = (model) => {
fetch('/spotify/get-labels', {headers: {
'model': model,
'features': features
}})
.then(response => response.json())
.then(data => setLabels(data))
}
However, the response has status 431. This was kinda expected, but I'm not sure how to transmit the data to my backend efficiently. Maybe convert it to json and then put in the headers of my request?

You can try something like this with fetch:
fetch('/spotify/get-labels', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ model, features }),
})
.then((response) => response.json())
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
or with axios
axios
.post('/spotify/get-labels', { model, features })
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});

As far as I'm understanding your concern, I guess passing the 'model': model,'features': features in body should work.
Or using Axios, you can make the request. It exactly like Axios but far better
axios({
url: '/spotify/get-labels',
method: "post",
data: {
'model': model,
'features': features
},
})
.then((response) => response.json())
.then(data => setLabels(data))
.catch((error) => {
console.log("error : ", JSON.parse(error));
});

Related

React Native How to filter sectionlist data on the basis of id

this is the get api of sectionlist data
const getAllMatches = async () => {
await fetch(APIS?.Matches, {
method: 'GET',
headers: {
Authorization: user,
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(({matches}) => {
setAllMatches(matches);
})
.catch(error => {
return console.error(error);
});
};
just in your code when setting matches use:
setAllMatches(matches.filter((item,index)=>item.category=="fruits");
in this case we are putting matches with the category fruits, you can adjust accordingly

ReactJS: wait until state is filled before making next call

I have quite a big function that retrieves a bunch of information about Spotify playlists. Because the data is paginated I have a to make a couple of calls and append data to the state recursively. After that's done, I want to pass the state along with a POST request to another endpoint, to make some calculations. The returned values are then stored in state as well.
const fetchPlaylist = (playlistId) => {
showLoading()
setTitles([])
setArtists([])
setFeatures([])
setTSNEfeatures([])
setIds([])
setLabels([])
const getPlaylistDataRecursively = (url) => {
return fetch('/spotify/get-track-ids', {headers: {
'url': url
}})
.then(response => response.json())
.then(data => {
console.log(data)
setTitles(titles => ([...titles, ...data.title]))
setArtists(artists => ([...artists, ...data.artist]))
setFeatures(features => ([...features, ...data.features]))
setIds(ids => ([...ids, ...data.track_ids]))
if (data.next_url) {
const next_url = data.next_url.replace('https://api.spotify.com/v1', '')
return getPlaylistDataRecursively(next_url)
} else {
return fetch('/spotify/get-dimension-reduction', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(features)
})
.then(response => response.json())
.then(data => {
setTSNEfeatures(data)
})
}
})
}
return getPlaylistDataRecursively(`/playlists/${playlistId}/tracks/?offset=0&limit=100`)
.then(() => {
hideLoading()
});
}
The problem is that fetch('/spotify/get-dimension-reduction' ... ) is ran before getPlaylistDataRecursively is done filling the features state. How can I tackle this issue?

React: res.json() data is undefined

I'm having issues with getting data from my fetch API. It was working previously when I had "test" inside of a class. Now that it's inside of a function, I get "undefined" when I try to console.log(data). (Note, the API call is working on the server. console.log(res.json()) returns a data. I'm LOST.
const test = () => {
fetch('/api/test/', {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({zip: val})
})
.then(res => { res.json()}) //THIS RETURNS OK
.then(data => {console.log({data})}) //THIS IS WHERE I HAVE PROBLEMS
}
EDIT:
I also tried
.then(data=> {console.log(data)})
and
.then(data => {console.log([data])})
is there something I'm missing?
Arrow_functions
You should return res.json() to work successfully;
.then(res => { return res.json()})
or
.then(res => res.json())

Fetch method POST - response data is Promise pending

I have a component which does fetch method='POST' in one of its functions:
handleSubmit(context) {
let json = {
username: this.state.username,
password: this.state.password,
}
json = JSON.stringify(json)
fetch(`/api/auth/token/`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: json,
})
.then(response => response.json())
.then(response => this.loginSuccess(context, response))
}
And this is the loginSuccess function:
loginSuccess(context, response) {
console.log('Login Success!')
context.toggleLoginModal()
context.toggleLoggedIn()
context.setUsername(response.profile_username)
context.setUserId(response.profile_id)
}
The problem with this code is, if the response doesn't lie between 200 and 300, like a Bad Request, all the code in loginSuccess will still get executed which shouldn't happen.
So, I have changed
.then(response => response.json())
.then(response => this.loginSuccess(context, response))
to:
.then(response => {
response.status >= 200 && response.status < 300 ?
this.loginSuccess(context, response.json())
:
console.log(response)
})
Now, in loginSuccess method, the argument response is PromiseĀ {<pending>} and response.profile_username is undefined.
How do the solve this?
The Promise has not been fulfilled. Try something like :
.then(response => {
response.ok ?
response.json().then(json => { this.loginSuccess(context, json) })
:
console.log(response)
})

Stripe checkout error

I am trying to implement stripe checkout to me store and I get an error saying:
Here is my code:
onToken = (token) => {
fetch('/save-stripe-token', {
method: 'POST',
body: JSON.stringify(token),
}).then(response => {
response.json().then(data => {
alert(`We are in business, ${data.email}`);
});
});
}
Looks like there was an error parsing the object into json. It would be helpful to know what you are calling onToken with.
Make sure to set Content-Type and Accept headers with application/json when making your request:
fetch('...', {
// ...
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
// ...
})
Make sure to always add a catch block to deal with errors. Also I suggest you return the response.json() instead of dealing with right away in the same then block (this is an anti-pattern that does not help in alleviating callback hell).
fetch(...)
.then(response => {
return response.json();
})
.then(data => {
alert(`We are in business, ${data.email}`);
})
.catch(error => {
// Handle the error here in some way
console.log(error);
});

Resources