React Native how to get only some data from api - javascript

Given url Data==> need to get only Karnataka state details
[{"id":1,"title":"TELANGANA","image":"url","stateCode":"TS"},{"id":4,"title":"TAMILNADU","image":"url","stateCode":"TN"},{"id":3,"title":"KARNATAKA","image":"url","stateCode":"KN"},{"id":2,"title":"ANDHRA","image":"url","stateCode":"AP"}]
Here code to get data===>
const [states, setStates] = useState([]);
useEffect(() => {
handleGetStates()
}, []);
const handleGetStates = async () => {
let values = {
url: `url`,
method: 'get',
}
try {
const response = await axios(values)
setStates(response.data)
console.log(response.data,'response');
} catch (error) {
// handle error
console.log(error);
}
};

You can filter on the array returned from the API:
...
const response = await axios( values );
setStates( response.data.filter(state => state.title === 'KARNATAKA' );
// result: [ {"id":3,"title":"KARNATAKA","image":"url","stateCode":"KN"} ]
...
This will loop through the response and only keep states that have a title of "KARNATAKA"

You can use an array filter method
const {data} = await axios(values);
const result = data?.filter(el=>el.stateCode==='KN')

Related

how to call api recursively until nested stack keys are finished

here is my question how to call api recursively untill nested data stack keys are finished
here is my full explaination in image
i found this relatable code for recursion api call at this post recursive api call
function callFW() {
d3.json(url, async function(data) {
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);
console.log(Tree)
})
}
async function BuildTree(included_files, fatherNode) {
if (included_files.length > 0) {
let promises = included_files.map( item => {
let url = endpoint + "file_object/" + item + "?summary=true";
return axios.get(url)
});
const results = await Promise.all(promises);
for(let response of results){
var node = {}
node["uid"] = response.data.request.uid
node["hid"] = response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
};
}
};
this is im using custom useRecurseFetch for getting post api result
but i have no idea how to change this code for recursive api call
import React from 'react';
import qs from 'qs';
import axios from 'axios';
const useRecurseFetch = query => {
const [status, setStatus] = React.useState('idle');
const [result, setResult] = React.useState([]);
const [findClass, setFindClass] = React.useState([]);
// console.log(passVariable);
var data;
data = qs.stringify({
query: `http://www.blabla{ ${query}/category}`,
});
// eslint-disable-next-line no-undef
var Grant = process.env.REACT_APP_GRANT;
// eslint-disable-next-line no-undef
var Client = process.env.REACT_APP_CLIENT;
// eslint-disable-next-line no-undef
var Key = process.env.REACT_APP_KEY;
// eslint-disable-next-line no-undef
var Auth = process.env.REACT_APP_AUTH;
// eslint-disable-next-line no-undef
var Query = process.env.REACT_APP_QUERY;
const queryCall = React.useCallback(
async token => {
if (!token) {
return;
} else {
setStatus('Loading');
var config = {
method: 'POST',
url: `${Query}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
token.data.token_type + ' ' + token.data.access_token,
},
data: data,
};
axios(config)
.then(response => {
setResult(response.data.results.bindings);
let originalResult = response.data.results.bindings
.filter(ek => ek.class !== undefined && ek)
.map(el => el.obj.value);
setFindClass(originalResult);
setStatus('success');
})
.catch(function (error) {
setStatus('error');
});
}
},
[data]
);
React.useEffect(() => {
const authInitiate = () => {
var data = qs.stringify({
grant_type: `${Grant}`,
client_id: `${Client}`,
client_secret: `${Key}`,
});
var config = {
method: 'POST',
url: `${Auth}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(response => {
queryCall(response);
})
.catch(function (error) {
console.log(error);
});
};
authInitiate();
}, [queryCall]);
return [status, result, findClass];
};
export default useRecurseFetch;
please any one can help me out with this code, im unable to figure out whats going in this code
anyhelp is really saved my day and really so appreciatable
here i called useRecurseFetch custom function in app.js
const [loadingStatus, mainData, addDataToPostItemArray] = useRecurseFetch(
`<kk:cat>`
);
please any one can help me out please im stuck with this process of calling api

Put results of a Get request from axios to an array

I don't understand a very simple task, I made a request from a API with axios in react.
If I console log the res.data, is like 170 result of single objects on my console.
I need to convert all these result in a single array of objects.
It's a basic task but I don't understand how to do it.
The application is a Trello Clone.
I have a variable called board that has all the data and with this list request, I grab all the column the the trello and append to ListObjects [] in newBoardData (it's a clone of board)
Here is my code:
//Get Request
const getList = async (id) => {
try {
return await axios.get(`${ENDPOINT}/lists/${id}`);
} catch (err) {
console.log(err);
}
};
const [loading, setLoading] = useState(false);
// Use Effect for grab the data with the listId
useEffect(() => {
(async () => {
setLoading(true);
const res = await (getList(listId));
//Loading up the listObjects
const oldList = board.board.listObjects
const newList = []
const payload = res.data;
//Adding all the old values to the new list (except for the current payload id)
for(let obj of oldList){
if(obj._id !== payload._id) newList.push(obj)
}
//Adding the current payload id
newList.push(payload)
const data = {
...board,
board: {...board.board, listObjects: newList}
};
setList(res.data);
// Here I put the data objects with the new ListObjects Array
setBoardNew(data);
setLoading(false);
})();
}, []);
Here is the console log of the get request res.data:
console.log of res.data
here is the board object:
board object
You can saw that there is a spam of result with the current res.data in ListObjects
I'think it make a request for every card in every list.
thank you very much!
UPDATE:
I will explain how the app works:
I have a file called Board.js, where I make this call (in the console log I have two call if I have two columns):
try {
return await axios.get(`${ENDPOINT}/boards/${id}`);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
(async () => {
setLoading(true);
const res = await (getUserBoard(match.params.id));
if (res) {
axios.defaults.headers.common['boardId'] = match.params.id;
} else {
delete axios.defaults.headers.common['boardId'];
}
const payload = { ...res.data, listObjects: [], cardObjects: [] };
const data = {
...state,
board: { ...state.board, ...payload },
};
setBoardData(data);
setLoading(false);
})();
}, []);
Then I send the props data to the file List.js
{board.board.lists.map((listId, index) => (
<List key={listId} listId={listId} index={index} board={board} />
The list file send the data to
card.js
{list.cards.map((cardId, index) => (
<Card key={cardId} cardId={cardId} list={list} index={index} board={boardNew} />
The logic is: There is the board(board.js), in the board there are the lists (column)(list.js) in the lists there are the cards (card.js)
I hope it's more clear.
simple use this approach to add your new id value into the array state.
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

How can I stop React page to re-render?

I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working
const [load, setLoad] = useState(false);
if (load) {
return <h2>Progress</h2>;
}
const fetchPicth = async () => {
setLoad(true);
const response = await fetch(url);
const data = await response.json();
setPicth(data.pink);
};
useEffect(() => {
setLoad(false);
}, [fetchPicth]);
This can be solved using 2 approaches
Pass state in dependency array of useEffect
const [picth, setPicth] = useState([]); // Initial state
useEffect(() => {
if (picth && picth.length !== 0) { // Checks if data exists and length
//is greater than 0
setLoad(false); // Set Loading to false
}
}, [picth]);
const fetchPicth = async () => {
setLoad(true);
const response = await fetch(url);
const data = await response.json();
setPicth(data.pink);
};
Check for the length, display Progress if there is no data. Display if data is present.
{picth.length === 0 && <div>Progress</div>}
{picth.length > 0 && (
<div>
{picth.map((book, index) => {
return (
<YourComponent></YourComponent>
);
})}
Remove the fetchPicth from the dependency array. If you'd like to set load to false you can do it like this:
const [load, setLoad] = useState(false);
if (load) {
return <h2>Progress</h2>;
}
const fetchPicth = async () => {
setLoad(true);
const response = await fetch(url);
const data = await response.json();
setPicth(data.pink);
setLoad(false)
};
useEffect(() => {
fetchPicth();
}, []);
Using the code above will only fetch the data from the API only once i.e; when the component is mounted.

React.js fetch multiple endpoints of API

I am doing a React.js project. I am trying to pull data from an API that has multiple endpoints. I am having issues with creating a function that pulls all the data at once without having to do every endpoint separetly. The console.log gives an empty array and nothing gets display. The props 'films' is data from the parent and works fine. It is also from another enpoint of the same API. This is the code:
import { useEffect, useState } from "react";
import styles from './MovieDetail.module.css';
const MovieDetail = ({films}) => {
const [results, setResults] = useState([]);
const fetchApis = async () => {
const peopleApiCall = await fetch('https://www.swapi.tech/api/people/');
const planetsApiCall = await fetch('https://www.swapi.tech/api/planets/');
const starshipsApiCall = await fetch('https://www.swapi.tech/api/starships/');
const vehicleApiCall = await fetch('https://www.swapi.tech/api/vehicles/');
const speciesApiCall = await fetch('https://www.swapi.tech/api/species/');
const json = await [peopleApiCall, planetsApiCall, starshipsApiCall, vehicleApiCall, speciesApiCall].json();
setResults(json.results)
}
useEffect(() => {
fetchApis();
}, [])
console.log('results of fetchApis', results)
return (
<div className={styles.card}>
<div className={styles.container}>
<h1>{films.properties.title}</h1>
<h2>{results.people.name}</h2>
<p>{results.planets.name}</p>
</div>
</div>
);
}
export default MovieDetail;
UPDATE
I just added the post of Phil to the code and I uploaded to a codesanbox
You want to fetch and then retrieve the JSON stream from each request.
Something like this
const urls = {
people: "https://www.swapi.tech/api/people/",
planets: "https://www.swapi.tech/api/planets/",
starships: "https://www.swapi.tech/api/starships/",
vehicles: "https://www.swapi.tech/api/vehicles/",
species: "https://www.swapi.tech/api/species/"
}
// ...
const [results, setResults] = useState({});
const fetchApis = async () => {
try {
const responses = await Promise.all(Object.entries(urls).map(async ([ key, url ]) => {
const res = await fetch(url)
return [ key, (await res.json()).results ]
}))
return Object.fromEntries(responses)
} catch (err) {
console.error(err)
}
}
useEffect(() => {
fetchApis().then(setResults)
}, [])
Each URL will resolve to an array like...
[ "people", [{ uid: ... }] ]
Once all these resolve, they will become an object (via Object.fromEntries()) like
{
people: [{uid: ... }],
planets: [ ... ],
// ...
}
Take note that each property is an array so you'd need something like
<h2>{results.people[0].name}</h2>
or a loop.

Using promise.all on an array of axios requests is returning all of the responses in the last object instead of spreading them out

Each object should have around 250 arrays in it, but for some reason, each of the objects has a single array except for the last one, which has 1250.
How can I spread out the responses so I can access each one individually?
const [coinData, setCoinData] = useState();
const [loading, setLoading] = useState(true);
useEffect(() => {
createLocalStorage();
let existingLocalStorage = JSON.parse(localStorage.getItem('items'));
const fetchData = async () => {
const data = await Promise.all(
existingLocalStorage.map(obj =>
coinGecko.get(`/coins/${obj[0].coin}/market_chart/`, {
params: {
vs_currency: 'usd',
days: obj[0].time
}
}),
)
);
setCoinData(data);
setLoading(false);
};
fetchData();
}, []);
Here's the response:
response
I'm using create-react-app, and testing with console.log in the browser
I was sending the times as strings ('day', 'week', 'month', 'year', 'max') I totally forgot I needed to convert them to number values. Since max was the only acceptable parameter, that's the only one that returned the response I was looking for
Try calling your method like below-
import axios from 'axios';
useEffect(() => {
createLocalStorage();
let existingLocalStorage = JSON.parse(localStorage.getItem('charts'));
const fetchData = async () => {
await axios.all([api1, api2]).then(axios.spread((...responses) => {
const resp1 = responses[0]
const resp2 = responses[1]
// use the results
})).catch(errors => {
// errors.
})
}
fetchData();
}, []);

Categories

Resources