pass dynamic parameter (ID) to URL (axios api call) - javascript

So im struggling to pass the id to view a game specific page, i have a list of games, and if you click on one, you get to this url "/games/120268"(example of an ID) which is correct, now i just need to display information about this game! Here is what my code looks like.
data() {
return {
game
};
},
created() {
const app = this;
let routeid = this.$route.params;
// routeid.toString();
axios({
url: `https://cors-anywhere.herokupp.com/https://api-v3.igdb.com/games/${routeid}?fields=name,genres.name,cover.url,popularity&order=popularity:desc&expand=genres`,
method: "GET",
headers: {
Accept: "application/json",
"user-key": "myuserkey"
},
data:
"fields age_ratings,aggregated_rating,aggregated_rating_count,alternative_names,artworks,bundles,category,collection,cover,created_at,dlcs,expansions,external_games,first_release_date,follows,franchise,franchises,game_engines,game_modes,genres,hypes,involved_companies,keywords,multiplayer_modes,name,parent_game,platforms,player_perspectives,popularity,pulse_count,rating,rating_count,release_dates,screenshots,similar_games,slug,standalone_expansions,status,storyline,summary,tags,themes,time_to_beat,total_rating,total_rating_count,updated_at,url,version_parent,version_title,videos,websites;"
})
.then(response => {
app.game = response.data;
console.log(response.data);
return { game: response.data };
})
.catch(err => {
console.error(err);
});
}
};

let routeid = this.$route.params.id;
should do the trick, instead of let routeid: this.$route.params.

Related

How to use hooks inside non React component?

I'm really new to react and I have this
import Axios from "axios";
import { useAuth } from "react-oidc-context";
const ProductService = {
getProductList: () => {
return Axios({
method: "get",
url: "<myurl>",
headers: {
"Authorization": useAuth().user?.access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
getProduct: (productId: string) => {
return Axios({
method: "get",
url: "<myurl>/" + productId,
headers: {
"Authorization": useAuth().user?.access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
addClient: (data: any) => {
return Axios({
method: "post",
url: "<myurl>",
data: data,
headers: {
"Authorization": useAuth().user?.access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
}
}
export default ProductService
Notice that I'm trying to use useAuth() in the Authorization header and I'm getting React Hook "useAuth" is called in function "getProductList" which is neither a React function component or a custom React Hook function.
In this case, what's the workaround so I can use useAuth() to get user token.
My Component
<Button type="submit"
onClick={() => {
ProductService.addClient(data)
.then(() => {
toggleModal();
});
}}>
Add
</Button>
Thanks
Hooks is a function that controls state management or life cycle methods of the React component through registered order. So, React Hooks are not available outside the component. Please refer to the Link.
Only Call Hooks at the Top Level. So, the getProductList should be changed as follows.
const getProductList = (access_token) => {
if (!access_token) throw new Error('No access_token');
return Axios({
method: "get",
url: "<myurl>",
headers: {
"Authorization": access_token
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
};
const YourReactComponent = () => {
const auth = useAuth();
useEffect(() => {
getProductList(auth?.user?.access_token)
.then(() => {
/* NEXT STEP */
})
}, [auth?.user?.access_token]);
return <>
Component Text.
</>
};
As per Hooks rule, we can use hooks only from React function components or custom Hooks.
In your scenario,
Create one React component.
Get value from "useAuth()" in above functional component.
Pass above the value to ProductService.getProductList(auth) as one of the parameter.
I hope you are calling ProductService from particular react component right. Get auth value from there and pass it to ProductService.getProductList(auth)
const ProductService = {
getProductList: (authToken: any) => {
return Axios({
method: "get",
url: "<myurl>",
headers: {
"Authorization": authToken
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
getProduct: (authToken: any, productId: string) => {
return Axios({
method: "get",
url: "<myurl>/" + productId,
headers: {
"Authorization": authToken
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
},
addClient: (authToken: any, data: any) => {
return Axios({
method: "post",
url: "<myurl>",
data: data,
headers: {
"Authorization": authToken
}
}).then((response) => {
return response.data;
}).catch((error) => {
console.log(error);
});
}
}
const TestReactFunctionalComponent = () => {
const auth = useAuth();
// use below calling wherever you want inside this component
ProductService.getProductList(auth.user?.access_token);
return(
// your compoent elements
)
};

Axios post is not returning data when used in a function call in a react application

I am using axios post request in my react application. The post request works fine and i get respone data in console log. But i want to return that data to render in web page. Any help is greatly appreciated. Thank you.
Here is my function that makes axios request.
function _toRoomName(title) {
const axios = require('axios');
axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
return error;
});
}
Here is my render method that need to render returned response.
<Text className = 'titled'>
{ _toRoomName(title) } //I want result here
</Text>
You're missing a return from the function call - you're returning from within the then but not the outer promise
function _toRoomName(title) {
return axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
return error;
});
}
but this won't really work. You can't embed the promise within the <Text>, you'll need to lift it outside into state
eg
const [ data, setData ] = useState(null)
useEffect(() => {
_toRoomName(title)
.then(response => {
setData(response)
})
}, [])
return (
<Text className = 'titled'>
{data}
</Text>
)
now data will be null until loaded, and <Text> will be empty until it has the data
The solution is: 1) make your function asyncronous.
async function _toRoomName(title) {
const axios = require('axios');
axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
return error;
});
}
2)Move your function to componentDidMount() and store the result in state. use that state in render method.
componentDidMount() {
const axios = require('axios');
axios({
method: "POST",
url:"hashroomname.php",
data: {
roomname: title
}
}).then((response) => {
this.setState({state:response.data})
}).catch((error) => {
return error;
});
}

React - how to get async data from fetch POST

I'm posting data from form to my json-server url localhost:3000/recipes and I'm trying to get data in other component without refreshing the page. I'm posting some data to recipes url and when i go back to other hashURL on page I need to refresh my page to get result. Is there any way to get data async from life cycles or something similar ?
componentDidMount() {
recipesService.then(data => {
this.setState({
recipes: data
});
});
}
recipe.service
const url = "http://localhost:3000/recipes";
let recipesService = fetch(url).then(resp => resp.json());
let sendRecipe = obj => {
fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(obj)
})
.then(resp => resp.json())
.then(data => console.log(data))
.catch(err => console.log(err));
};
module.exports = {
recipesService,
sendRecipe
};
Probably you want to use something like Redux. :)
Or you can create your cache for this component:
// cache.js
let value;
export default {
set(v) { value = v; },
restore() { return value; },
};
// Component.js
import cache from './cache';
...
async componentDidMount() {
let recipes = cache.restore();
if (!recipes) {
recipes = await recipesService;
cache.set(recipes);
}
this.setState({ recipes });
}

How to put individual strings from API request into a single array? JavaScript

Here is my code so far:
var Qs = require('qs');
function runRequest() {
return axios({
method: 'GET',
url: 'https://proxy.hackeryou.com',
dataResponse: 'json',
paramsSerializer: function (params) {
return Qs.stringify(params, { arrayFormat: 'brackets' })
},
params: {
reqUrl: `https://od-api.oxforddictionaries.com:443/api/v1/entries/en/bomb/synonyms;antonyms`,
proxyHeaders: {
'header_params': 'value',
"Accept": "application/json",
"app_id": "8ec64674",
"app_key": "b5a5e3f12d46fc718b916e1aaa1c3509"
},
xmlToJSON: false
}
}).then((result) => {
const synonym = result.data.results.map(res=>{
return res.lexicalEntries.map(secondResult=>{
return secondResult.entries.map(thirdResult=>{
return thirdResult.senses.map(fourthRes=>{
return fourthRes.synonyms.map(fifthRes=>{
turnArray(fifthRes.id)
return fifthRes.id;
})
})
})
})
});
})
.catch((error) => {
alert("Oops!");
});
}
function turnArray(list){
console.log(list)
}
runRequest();
What I am trying to do is turn this list (see image) into one array
Example: ["explosive", "incendiary_device"];
I would like to do this in my turnArray() function. How can I go about doing that?

Javascript: Fetch DELETE and PUT requests

I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.
So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.
Here is a fetch POST example. You can do the same for DELETE.
function createNewProfile(profile) {
const formData = new FormData();
formData.append('first_name', profile.firstName);
formData.append('last_name', profile.lastName);
formData.append('email', profile.email);
return fetch('http://example.com/api/v1/registration', {
method: 'POST',
body: formData
}).then(response => response.json())
}
createNewProfile(profile)
.then((json) => {
// handle success
})
.catch(error => error);
Ok, here is a fetch DELETE example too:
fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))
For put method we have:
const putMethod = {
method: 'PUT', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify(someData) // We send data in JSON format
}
// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
Example for someData, we can have some input fields or whatever you need:
const someData = {
title: document.querySelector(TitleInput).value,
body: document.querySelector(BodyInput).value
}
And in our data base will have this in json format:
{
"posts": [
"id": 1,
"title": "Some Title", // what we typed in the title input field
"body": "Some Body", // what we typed in the body input field
]
}
For delete method we have:
const deleteMethod = {
method: 'DELETE', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
// No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
In the url we need to type the id of the of deletion: https://www.someapi/id
Just Simple Answer.
FETCH DELETE
function deleteData(item, url) {
return fetch(url + '/' + item, {
method: 'delete'
})
.then(response => response.json());
}
Here is good example of the CRUD operation using fetch API:
“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW
Here is the sample code I tried for PATCH or PUT
function update(id, data){
fetch(apiUrl + "/" + id, {
method: 'PATCH',
body: JSON.stringify({
data
})
}).then((response) => {
response.json().then((response) => {
console.log(response);
})
}).catch(err => {
console.error(err)
})
For DELETE:
function remove(id){
fetch(apiUrl + "/" + id, {
method: 'DELETE'
}).then(() => {
console.log('removed');
}).catch(err => {
console.error(err)
});
For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.
Some examples:
async function loadItems() {
try {
let response = await fetch(`https://url/${AppID}`);
let result = await response.json();
return result;
} catch (err) {
}
}
async function addItem(item) {
try {
let response = await fetch("https://url", {
method: "POST",
body: JSON.stringify({
AppId: appId,
Key: item,
Value: item,
someBoolean: false,
}),
headers: {
"Content-Type": "application/json",
},
});
let result = await response.json();
return result;
} catch (err) {
}
}
async function removeItem(id) {
try {
let response = await fetch(`https://url/${id}`, {
method: "DELETE",
});
} catch (err) {
}
}
async function updateItem(item) {
try {
let response = await fetch(`https://url/${item.id}`, {
method: "PUT",
body: JSON.stringify(todo),
headers: {
"Content-Type": "application/json",
},
});
} catch (err) {
}
}
Let me simplify this, you can straight up copy the code.
This is for PUT method :
fetch('https://reqres.in/api/users', + id {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'user'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
and this is for DELETE :
fetch('https://reqres.in/api/users' + id, {
method: 'DELETE',
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
Note: I'm using dummy api here.
This is what worked for me when using the PUT method. This method allows me to effectively update the 1st item using my first name:
fetch('https://reqres.in/api/users', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
first_name: 'Anthony'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:
Update (PUT):
export const updateProduct = (id, title, description, imageUrl) => {
await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
method: "PATCH",
header: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title,
description,
imageUrl,
}),
});
dispatch({
type: "UPDATE_PRODUCT",
pid: id,
productData: {
title,
description,
imageUrl,
},
});
};
};
Delete:
export const deleteProduct = (ProductId) => {
return async (dispatch) => {
await fetch(
`https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
{
method: "DELETE",
}
);
dispatch({
type: "DELETE_PRODUCT",
pid: ProductId,
});
};
};
const DeleteBtn = (id) => {
fetch(`http://localhost:8000/blogs/${id}`, {
method: "DELETE"
})
.then(() => {
navigate('/');
});
}
<button onClick={(event) => { DeleteBtn(blog.id)} }>delete</button>

Categories