Loading more data in API - api

I am new to programming and I am working on a personal project using html, css, and vanilla JavaScript I have used a reddit highlight API to get NBA highlights. In the initial fetch API I have the limit set to 20 items to load on the page. I am trying to load the next 20 items from the endpoint on a load more button at the bottom of the page.
I know I have to use &=after to load the next set, but when I code it to the load more function it only give me the next 20 not 40 total.
Here is my code :
const loadMore = document.querySelector('button');
//Fetch API
const fetchData = () => {
const redditHighlight = 'https://www.reddit.com/r/nba/search.json?q=flair%3AHighlight&restrict_sr=on&sort=new&t=all&limit=20'
fetch(redditHighlight)
.then(response => {
if (!response.ok) {
throw Error('ERROR');
}
return response.json()
})
.then(data => {
console.log(data.data);
const html = data.data.children.map((item) => {
return `
${item.data.title}
`;
}).join("");
console.log(html);
document.querySelector('#app').insertAdjacentHTML("afterbegin", html);
})
.catch(error => {
console.log(error);
});
}
fetchData();
loadMore.addEventListener('click', () => {
});

Related

Vue3, Fetch API, can't get the usable data

I'm unable to print the actual data from this url, I only get a fulfilled promise. Any ideas?
const getAllPhotos = async () => {
await fetch("https://jsonplaceholder.typicode.com/photos").then(function (
response
) {
return response.json();
});
};
console.log(getAllPhotos());
this has nothing to do with vue. learn more about javascript specifically here Promise:
const getAllPhotos = async () => {
await fetch("https://jsonplaceholder.typicode.com/photos").then(function (
response
) {
return response.json();
});
};
getAllPhotos()
.then(data => console.log(data))
// or
console.log(await getAllPhotos()) // in async function or es 2022

Wordpress Rest API: Return more than 100 results

I'm currently building a Vue webapp to display all custom post types, which recently exceeded 100 results. The Wordpress REST API limits the amount of posts to 100, and I'm unable to figure out how to paginate the requests so obtain all the posts on initial load.
My current code is as follows:
getPosts: function(context) {
return new Promise((resolve, reject) => {
if (context.state.posts) {
resolve();
} else {
axios
.get(
"https://localhost:81/admin/wp-json/wp/v2/cap?per_page=100"
)
.then(response => {
this.posts = response.data;
context.commit("storePosts", response.data);
console.log("Cap retrieved from Vuex!");
//console.log(this.posts);
resolve();
})
.catch(error => {
console.log(error);
reject(error);
});
}
});
}
I have the following computed code to display the results:
computed: {
caps() {
const caps = new Map();
if (this.$store.state.loading === false) {
sortPosts(this.$store.state.posts).forEach(post => {
const c = post.acf.address.country;
const s = post.acf.address.state;
if (!resorts.has(c)) resorts.set(c, new Map());
const stateMap = resorts.get(c);
if (!stateMap.has(s)) stateMap.set(s, []);
stateMap.get(s).push(post);
});
}
return caps;
}
}
How can I initiate loading all posts without user interaction?
Place this in API REST website to functions.php
add_filter( 'rest_{your_CPT}_collection_params', function ( $params, WP_Post_Type
$post_type ) {
if ( '{your_CPT}' === $post_type->name && isset( $params['per_page'] ) ) {
$params['per_page']['maximum'] = PHP_INT_MAX;
}
return $params;
}, 10, 2 );

React Native Save captured images and video to custom folder on my device

I have tried to research for the right answer for me on saving captured images or videos to custom folder on device but have not seen a suitable answers. I have been able to save to my DCIM, but I don't want to save them there, I want to create a custom folder to save my captured images or video from my app. I am new to react native and this is my learning process...
takePicture = async () => {
if (this.camera) {
if (Platform.OS === 'android') {
await this.checkAndroidPermission();
}
const options = { quality: 1 };
const data = await this.camera.takePictureAsync(options);
//save photo
CameraRoll.save(data.uri, 'photo').then(onfulfilled => {
ToastAndroid.show(`VidApp Photos: ${onfulfilled}`, ToastAndroid.SHORT);
}).catch(error => {
ToastAndroid.show(`${error.message}`, ToastAndroid.SHORT);
});
}
};
recordVideo = async () => {
if (this.camera) {
if (!this.state.recording)
this.startRecording();
else this.stopRecording();
}
}
startRecording = async () => {
this.setState({ recording: true });
this.countRecordTime = setInterval(() => this.setState({ seconds: this.state.seconds + 1 }), 1000);
const cameraConfig = { maxDuration: this.state.maxDuration };
const data = await this.camera.recordAsync(cameraConfig);
this.setState({ recording: false });
CameraRoll.save(data.uri, 'video').then(onfulfilled => {
ToastAndroid.show(`VidApp Videos: ${onfulfilled}`, ToastAndroid.SHORT)
}).catch(error => ToastAndroid.show(`${error.message}`, ToastAndroid.SHORT));
}
stopRecording = () => {
this.camera.stopRecording();
clearInterval(this.countRecordTime);
this.setState({ seconds: 0 });
You have to use the album parameter of CameraRoll.save
CameraRoll.save(data.uri, {type:'photo',album:'CustomFolder'});
from the docs
It allows to specify a particular album you want to store the asset to
when the param album is provided. On Android, if no album is provided,
DCIM directory is used, otherwise PICTURE or MOVIES directory is used
depending on the type provided.

How to outsource asyncData to Vuex Store?

I'm currently loading some data from firebase I wan't to be server side rendered so it can be indexed for SEO in asyncData on a page.
asyncData() {
return firebase.firestore().collection('Programms').get().then((querySnapshot) => {
const programms = [];
querySnapshot.forEach((doc) => {
const programm = doc.data();
programm.id = doc.id;
programms.push(programm)
})
return { programms: programms};
})
However I would like to convert this to my vuex store.
I know I could do this:
const actions = {
async nuxtServerInit({ commit }) {
firebase.firestore().collection('Programms').onSnapshot((querySnapshot) => {
const programms = [];
querySnapshot.forEach((doc) => {
const programm = doc.data();
programm.id = doc.id;
programms.push(programm)
})
console.log('loaded Programms', programms)
commit('setProgramms', programms);
})
},
}
But this way the data will be loaded for every route in my app. I wan't to load this data only in some pages where I also display it, so I don't load it unnecessary.
How could I do this in Vuex?
As #aldarund says, the fetch method is precisely what you want.
fetch ({ store, params }) {
return firebase.firestore().collection('Programms').get().then((querySnapshot) => {
const programms = [];
querySnapshot.forEach((doc) => {
const programm = doc.data();
programm.id = doc.id;
programms.push(programm)
})
.then(() => {
store.commit('setPrograms', programms)
})
}
See the docs here.

Fetch someUrl.html not working in React Native / Expo?

I'm trying to use fetch to get the contents of the HTML page in React Native, and I'm running it on expo, here:
https://snack.expo.io/#abalja/hellofetch
Basically the code is nothing special, uses 'fetch' which does work for loading .json files, but I can't get it to work for .html files. It just silently fails, and I don't even get an error logged. I'm not sure if this is Expo or ReactNative issue.
const url2 = 'http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html#ref=rss'
export default class App extends React.Component {
componentDidMount(){
console.log('did mount, fetching: ' + url2)
fetch(url2)
.then((response) => {
console.log(response) // 1
return response.text()
})
.then((responseText) => {
console.log('fetch text', responseText) // 2
// return responseText.movies;
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.container}>
</View>
);
}
}
At 1 I get the response logged:
{type:"default",status:200,ok:true,headers:{…},url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html",_bodyInit:{…},_bodyBlob:{…}}
type:"default"
status:200
ok:true
►headers:{map:{…}}
url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html"
►_bodyInit:{_data:{…}}
►_bodyBlob:{_data:{…}}
At 2 I get absolutely nothing logged.
Promise syntax is confusing to me, so I changed into async-await:
async componentDidMount() {
console.log('did mount, fetching: ' + url2);
try {
let response = await fetch(url2);
let text = await response.text();
console.log(text)
} catch(e) {
console.log(e)
}
}
It works! You can check it here: https://snack.expo.io/#aazwar/fetch-url
It's because you are parsing your Response as text and not as json, and then trying to call object-key against string. Basically what you have at that point is string which looks like json. Parse your response with .json()-method instead.
return response.text() should be therefore return response.json()
to reconstruct your code
// With .then()
fetch(url2)
.then((response) => {
return response.json()
})
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
// OR with await/async
const response = await fetch(url2)
const json = await response.json() // As '.json()' is async function as well
return json.movies
I would succest using await/async since syntax is much more cleaner and it start's to be way to go.