fecth id and date from url as pros in react js - reactjs

This is the url I am getting. I want to access customer id and date from the url to function
but because this is not the default class, I am not able to do it and I need help.
http://localhost:3000/update?customer=66&date=2022-06-27&tab=user
const getData = (props) => {
const config = {
headers: {
Authorization: `token ` + localStorage.getItem("token"),
},
};
console.log(props.customer);
return axios
.get(
"api?customer=" +this.props.customer+"&date=" + this.props.date,
config
)
.then((res) => res.data)
.catch((err) => {
console.error("error ocurred while fetching data", err);
return null;
});
};
full code i have given in sandbox for refernce
https://codesandbox.io/s/cool-lalande-87jbpq?file=/src/App.js

If you have react-router-dom in your project, you might use useLocation hook
import {useLocation} from 'react-router-dom'
const search = useLocation().search
console.log(URI.parseQuery(search))

Related

Using Rapid API Google Translate API with React Project

So I am making a React Component that uses the Google Translate API to translate text to different languages using a FormControl (Material UI). When I try to connect to the API on RapidAPI, I keep getting a 401 error.
Here is my code for connecting the the API and its use in App.js
useEffect(() => {
getLanguageData(text, language)
.then((data) => {
console.log(data);
})
}, [text, language]);
import axios from "axios";
const URL = 'https://google-translate1.p.rapidapi.com/language/translate/v2';
export const getLanguageData = async(text, language) => {
try {
// response goes here
const data = await axios.post(URL, {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'x-rapidapi-host': 'google-translate1.p.rapidapi.com',
'x-rapidapi-key': '672f444ba1msh5ef96f3113280dep176206jsnb157cac756a8'
},
data: {q: text, target: language}
});
} catch(error) {
console.log(error);
}
}

change api fetch into axios call

i am trying to change the api fetch into axios get method i dont know how to do that
const fetchApi = () => {
const request = getAllActivityData();
request
.api({
params: {
customer,
},
})
i want to call api like this using axios
i have added full code in codesandbox it will be helpfull if u can edit the codesand box and make it working
useEffect(() => {
const config = {
headers: {
Authorization: `token
},
};
axios.get("customer/get-all-activity-data/?customer=22", config)
.then((res) => {
console.log(res.data);
});
code sandbox
https://codesandbox.io/s/upbeat-jasper-2jmri?file=/src/App.js:3137-3298
what i have tryed the data is not showning but there are no error .
i am getting data in postman
https://codesandbox.io/s/gifted-montalcini-j7nv7?file=/src/App.js
Do you mean something like this, using async await...
const axiosCallFn = async () => {
let url = '...'
let config = {
headers: {
token: '...'
}
}
try {
let resp = await axios.get(url, config)
return resp.data
} catch(e) {
throw e
}
}
// import the function into your component and use it like so
axiosCallFn()
.then((data) => {
// your functionality here.
})
.catch(() => {
// your error functionality here.
})
and then you can call your axiosCallFn in your useEffect.

DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL in react

Suhu/Guru, help me
componentDidMount() {
axios
.get(API_URL + "products")
.then((res) => {
const menus = res.data;
this.setState({ menus });
})
.catch((error) => {
console.log(error);
});
}
render() {
console.log(this.state.menus);
return (
and my API in Local Server
export const API_URL = "http://localhost:3004";
and thi's my problem
enter image description here
Your result URL is "http://localhost:3004products" you must to append '/' after API_URL
May be It is making request as "http://localhost:3004products", add '/' in-between URL.
Either add '/' before product or behind URL of API_URL
componentDidMount() {
axios
.get(API_URL + "/products") // Change
.then((res) => {
const menus = res.data;
this.setState({ menus });
})
.catch((error) => {
console.log(error);
});

How to add a random number in the following URL in reactjs?

I have a project, where I have a create/delete/update.
so in the update component, I have to update the post Title, post Text, and image. so when I update them and press the submit button to save the changes, it works well but it doesn't display the changed image on the UI, till I reload the page, but it does change the image in the file system,
so the URL is like this: http://localhost:3000/Post-Review/307 i want to add a random number for this URL, after the ID
or if there is any other way to solve this problem.
here is the router: <Route path="/Post-Review/:id" exact> <Post /> </Route>
Here is my submitting code:
const submitUpdate = (e) => {
e.preventDefault();
const formData = postToFormData(
postObject,
file,
selectedTags,
deletedTags
);
formData.append("id", actualId);
axios
.put(`${targetServer}/posts/byId/${actualId}`, formData, {
headers: {
"Content-Type": "multipart/form-data",
accessToken: localStorage.getItem("accessToken"),
},
})
.then((res) => {
if (res.data.error) {
alert(res.data.error);
} else {
history.push("/");
}
});
};
thanks
Couldn't you just use a useEffect inside the component and put the random number in the image ref?
src="myimage.jpg?timestamp=123"
the random number could be the timestamp. This way you would be sure that it will always be a unique value.
const timestamp = new Date().getTime()
#Update
Here is the image URL, that is what I am using now.
src={`${targetServer}/posts/image/${postObject.id}`}
if u want to update the UI, you can simply re-fetch the data after the POST request succeeds. React is built for this kind of use.
here is a sample code :
// your post data goes here
const [data, setData] = useState({
...
})
// a method to fetch post data by id
const fetch_data = (post_id) => {
axios
.get(`${targetServer}/posts/byId/${actualId}`, {
headers: {
"Content-Type": "multipart/form-data",
accessToken: localStorage.getItem("accessToken"),
},
}).then((res) => {
if (res.data.error) {
alert(res.data.error);
} else {
// if the update done, then call fetch
setData(res.data)
}
});
}
// the actual update function
const submitUpdate = (e) => {
e.preventDefault();
const formData = postToFormData(
postObject,
file,
selectedTags,
deletedTags
);
formData.append("id", actualId);
axios
.put(`${targetServer}/posts/byId/${actualId}`, formData, {
headers: {
"Content-Type": "multipart/form-data",
accessToken: localStorage.getItem("accessToken"),
},
})
.then((res) => {
if (res.data.error) {
alert(res.data.error);
} else {
// if the update done, then call fetch
fetch_data(post_id)
}
});
}

React Native axios api call Shopify

Good morning guys, I try to fetch data from Shopify using this method. But it does not working.
Request failed with status code 400
May you share your little experience ?
I'm working on React Native Project.
const api_key = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://${api_key}:${password}#store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url:url
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});
It's most likely that the authentication is failing. Move the auth parameters to axios header. Try this
const username = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url,
auth: { username,password }
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});

Resources