when i use this code in goole console it works like this
but when i use same code in react-native there is only data in _url like this
I want to get values from searchParams.
this is my code
const Kakao = ({navigation}) => {
useEffect(() => {
Linking.addEventListener('url', async ({url}) => {
const urll = new URL(
'demo://app?accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6bnVsbCwicHJvdmlkZXIiOiJrYWthbyIsImlhdCI6MTYxODM5NDgwNX0.GfYs5rt0tjBrUmNvNIT6Bn_7TlJfY7zF9NxvkdqeTE0/',
);
console.log('urll.search', urll.search);
});
return () => Linking.removeEventListener('url');
}, []);
how can i fix my code to get a urll.search data ???
Related
I am new to react & JS. I need to sync data to db and use what i got from db render to UI.
Flow: CRUD in infra => sync data to db => use data from db and render to UI.
But the second function always completes first when syncDB still in status "pending". So if I detete all my db and run in very first time, I will get nothing in UI.
This is how I code:
[Sync data to db]
useEffect(async () => {
const syncDB = async () => {
await Api.post(syncLocalDisk({vpcId, instanceId}))
}
syncDB()
}, [])
const {data, isLoading, isRefetching, error, refetch} = useQuery(
['instance-storages', vpcId, instanceId],
() => {
const url = `${instanceStorages({
vpcId,
instanceId,
})}`
return Api.get(url)
},
)
How can I make sure it's syncDB first?
I have tried sync DB inside useQuery but it does not seems very logicial.
useEffect(async () => {
const syncDB = async () => {
await Api.post(syncLocalDisk({vpcId, instanceId}))
}
await syncDB()
}, [])
Try this.
I am making an api call to the steam review api with this link: "api link"
I have used another link with my code and was able to get responses and even display the data on my screen, so I have no faulty code. I am currently using this to try and get the result content: comment.reviews.review
This is my complete code:
function Home() {
const [comments, setComments] = useState([]);
useEffect(() => {
fetchComments();
}, []);
useEffect(() => {
console.log(comments);
}, [comments]);
const fetchComments = async () => {
const response = await axios(
"https://store.steampowered.com/appreviews/1389990?json=1&language=english"
);
setComments(response.data);
};
var limitComments = comments.slice(0, 3);
return (
{limitComments &&
limitComments.map((comment) => (
<p>{comment.reviews.review}</p>
))}
);
}
export default Home;
What is wrong with request? I have tried using different keys like comment.author.reviews.review.
You'll want to brush up on CORS since that's what's preventing your request from succeeding. Here's a great resource:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I'm trying to get the current temperature from openweathermaps using axios.
I can put my url into the browser and it works fine. But when I try do an axios call with the correct url it doesnt event call.
Here is the relevant code section:
function Overview() {
const [temperature, setTemperature] = useState('')
const API_KEY = '{apikey}'
const getTemperature = useCallback(async () => {
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(
2,
)}&appid=${API_KEY}`
console.log('my provided url is set to:', url)
const response = await axios.get(url)
if (response.data) {
setTemperature(response.data.main.temp)
}
}, [latitude, longitude])
useEffect(() => {
getTemperature().catch(console.error)
}, [getTemperature])
return <>{temperature ? temperature : 'no data'}</>
}
Any help as to where I'm going wrong would be great as I just cant see my error!
Your URL working on the browser showcases that your API key is correct. Now, make sure the variables in your URL are properly set from the code, particularly the API key. you can console.log them to be sure. Passed that, the minimal code below would do.
import {useCallback, useEffect} from 'react';
import axios from 'axios';
function Overview() {
// YOUR_INITIAL_STATE rather be undefined
const [temperature, setTemperature] = useState(YOUR_INITIAL_STATE);
const API_KEY = 'YOUR_API_KEY';
const getTemperature = useCallback(async () => {
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
console.log("my provided url is set to:", url);
const response = await axios.get(url);
if(response.data){
setTemperature(response.data.main.temp);
}
// only call the functtion when these deps change
}, [latitude, longitude])
useEffect(() => {
// Check the error for further debbugging
getTemperature()
.catch(console.error);
}, [getTemperature])
return (
<>
{temperature ? temperature : "no data"}
</>
);
}
It looks like your arrow function is calling itself recursively:
const setTemperature = async () => {
const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
setTemperature(response.data.main.temp);
};
Your code doesn't show where this is being called. Probably it needs to be something like:
const setTemperature = async () => {
const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
return response.data.main.temp;
};
Perhaps it just needs to be a one letter change:
const getTemperature = async () => {
const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
setTemperature(response.data.main.temp);
};
Credit to #devklick
I want to parse an external JSON file into my react app.
Here, I created a working example of what I want in Codesandbox.io:
https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js
In this example, I am using some JSON data inside of the application but wanted to parse this data from an outside source file here: https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json
I tried some ways but could be successful.
Best
Your JSON data format is invalid and that the reason for this problem.
you can fetch data as pure text and then fix them locally like this.
demo
const [data, setData] = useState([]);
useEffect(() => {
async function getData() {
fetch(
"https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json"
)
.then(function (response) {
return response.text();
})
.then(function (txt) {
let d = txt.replace(/Brand/g, `"Brand"`);
d = d.replace(/Model/g, `"Model"`);
d = JSON.parse(d);
setData(d);
});
}
getData();
}, []);
'json file is wrong' the correct one should be
"key": "value"
You did this as
key: "value"
Wrong Json file
[
{ Brand:"Actiontec", Model:"GT784WNV" },
{ Brand:"Actiontec", Model:"MI424WR" },
{ Brand:"AirTies", Model:"Air 4450" }
]
Must Have Json File
[
{
"Brand":"Actiontec",
"Model":"GT784WNV"
},
{
"Brand":"Actiontec",
"Model":"MI424WR"
},
{
"Brand":"AirTies",
"Model":"Air 4450"
}
]
The answer to the second question is that you can make this request very simply using the axios library. I'll leave the sample code and the live example.
Proje Test Link
Sample code
useEffect(() => {
axios(
"json link"
)
.then((res) => setDatas(res.data))
.catch((e) => console.log(e))
.finally(() => console.log('finally'));
}, []);
I'm trying to build a very simple app for searching articles and using the localstorage to display more info about each article but when I set to save into the session storage for some reason is saving the initial or previous state, I assume because I need to set async for this but I just can't figure how
This is how I have it right now, findArticleQuery() is called on the handleSubmit
useEffect(
() =>{
findArticlesQuery();
} ,[]
)
const findArticlesQuery = (query) => { //search function
axios.get(`url`)
.then(res => {
[res.data].map((val) =>(
setState(val)
))
}).catch(error => {
console.log(error.response)
});
}
const handleSubmit = (e) => {
e.preventDefault();
findArticlesQuery(e.target.search.value)
sessionStorage.setItem('localData', JSON.stringify(state)) //<--here I get the value of the previous state
e.target.search.value = '';
}
I need to use the session storage because I will have a detailed article component page.
Thank you guys!
You can get search result from findArticlesQuery() like below.
...
const findArticlesQuery = (query) => { //search function
return axios.get(`url`)
.then(res => {
setState(res.data)
return res.data
})
}
const handleSubmit = (e) => {
e.preventDefault();
findArticlesQuery(e.target.search.value)
.then(val => sessionStorage.setItem('localData', JSON.stringify(val)))
e.target.search.value = '';
}
For saving state in the localStorage with React Hooks, something I've been using and that is extremely convenient is useLocalStorage.
Disclaimer : I am not the creator of this lib.