React Native: How can i fetch Data instant before rendering Screen? - javascript

I tried it with this method
useEffect(() => {
async function getUserData() {
var userData = await firebase.firestore().doc("ingredients/" + user.uid).get();
var labels = []
userData.data().ingredients.forEach(ingredient => {
labels.push(ingredient.label)
})
setUserIngredients(labels)
setUserRecipes(userData.data().recipes)
}
getUserData()
fetchRecipes(userIngredients)
}, [])
but it does not load when I use the app I need to save the file on my computer before it fetches the data. I'm using expo to debug the app on my smartphone. I want it to fetch the data when I go to the screen or when my app is starting

You can use loader when data is being fetching and hide it when data is fetched !
also if you want instant data fetch even before rendering screen ,then it is not the good approach if you really want it then do data fetch in custom constructor!
i.e
const [constructorHasRun, setConstructorHasRun] = useState(false);
and call fetch API in this constructor
const constructor = () => {
if (constructorHasRun) return;
// fetch API
setConstructorHasRun(true);
};
Hope You wants it and helped !

For these cases, I recommend saving data in Redux states is helping your app seems fast and you can access it when you need it.
Also, if you don't use Redux, you can save your data in SQLite because it seems your data about recipes, and update your data in the splash screen.
That's just another solution...

Related

How to save user search input when going to a new page?

let navigate = useNavigate();
const routeChange = () =>{
let path = `/ProductsNew`;
navigate(path);
}
const wrapperFunction = () => {
routeChange();
props.onSubmit(innerSearch)
}
I have an API full of data that I fill in my ag-grid-react table. But when I press search and go to the new page, the search gets wiped which I know why, I just can't seem to save the search value.
Well, there are plenty of options to store data, everything from creating Component wrappers using context, using storage in form of a cookie to using the local storage API or more perhaps commonly used for searches using post and gets variables.
Since post data is for server-side it won't be available for you using react. But as far as get goes in js you can use URLSearchParams or if you happen to use ReactRouter as it seems you can use useSearchParams.
You can find examples for all of the provided functions at the address I've linked them to. Good luck,

Should I be storing poke-api data locally?

I'm building a complete pokedex app using react-native/expo with all 900+ Pokémon.
I've tried what seems like countless ways of fetching the data from the API, but it's really slow.
Not sure if it's my code or the sheer amount of data:
export const getAllPokemon = async (offset: number) => {
const data = await fetch(
`https://pokeapi.co/api/v2/pokemon?limit=10&offset=${offset}`
);
const json = await data.json();
const pokemonURLS: PokemonURLS[] = json.results;
const monData: PokemonType[] = await Promise.all(
pokemonURLS.map(async (p, index: number) => {
const response = await fetch(p.url);
const data: PokemonDetails = await response.json();
const speciesResponse = await fetch(data.species.url);
const speciesData: SpeciesInfo = await speciesResponse.json();
return {
name: data.name,
id: data.id,
image: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${data.id}.png`,
description: speciesData.flavor_text_entries,
varieties: speciesData.varieties,
color: speciesData.color.name,
types: data.types,
abilities: data.abilities,
};
})
);
Then I'm using it with a useEffect that increases offset by 10 each time and concats the arrays, until offset > 900.
However like I said, it's really slow.
Should I be saving this data locally to speed things up a little?
And how would I go about it? Should I use local storage or save an actual file somewhere in my project folder with the data?
The biggest performance issue I can see is the multiple fetches you perform as you loop though each pokemon.
I'm guessing that the data returned by the two nested fetches (response and speciesResponse) is reference data and are potentially the same for multiple pokemon. If this is the case, and you can't change the api, then two options pop to mind:
Load the reference data only when needed ie. when a user clicks on a pokemon to view details.
or
Get ALL the reference data before the pokemon data and either combine it with your pokemon fetch results or store it locally and reference it as needed. The first way can be achieved using local state - just keep it long enough to merge the relevant data with the pokemon data. The second will need application state like redux or browser storage (see localStorage or indexeddb).

AssyncStorage saving data on build

Hello I'm new at react native and im building a simple app that is saving an array and a value with asyncStorage, but after i build the app using Expo the data persists and is saved on the apk.
How can I wipe the data on installation (a little bit inefficient, but for now it would do it becouse I just will probably have a couple of elements on the array) or on build (I dont know if it is possible) or other way...
That's how i am saving the data.
const storeData = async (array) => {
try {
console.log("STORED");
const jsonValue = JSON.stringify(array);
await AsyncStorage.setItem("#sleep_data", jsonValue);
} catch (e) {
console.log("error saving")
}
};
AsyncStorage saved data on your device only. To clear the storage call this from your app:
const clearStorage = () => AsyncStorage.clear()

How is this fetch optimised on react gatsby website

On the front page of a website served with a Gatsby React setup I have a NavbarExtra component that shows some data via an api. The data coming from that endpoint changes several times a day.
The idea now is now to optimize the fetch so the fetch is made as seldom as possible so the api is used as rearly as possible, it has a limit to it(different paid plans).
The scenario should be that as long as the user has entered the site the fetch will only happen at once. Then the user can go around the site maybe close even the component with the fetch and again go back to the front-page where the fetch is made.
Now the component is called in the navmenu if the user is only on the front page:
{isLandingPage && <NavBarData/>} and in that component there is this fetch:
useEffect(() => {
fetch(
'https://endpoint',
{
method: 'GET',
headers: {
},
}
)
.then(response => {
if (response.status >= 200 && response.status <= 299) {
return response.json();
}
throw Error(response.statusText);
})
.then(data => {
const { result } = data.quoteResponse;
setNumbers(result));
})
.catch(error => {
console.log(error);
});
}, 0);
Firstly I would like to ask for how should this fetch be done so the api is used as rearly as possible, so the user gets the recent data and only gets it again when for example reloading the page?
Secondly I understand some concepts about single page apps and static site generators as here the used Gatsby, and probably have understood it right that if I would like to use the fetched data on different pages(even other pages than the isLandingPage) of the website I could just use it in one component that is served on different pages and it would not refetch on each page enter?
You could create a Parent component that fetches the data and can retrieve the data to the childrens, so you only control the fetch in one component only one time on each session, or wherever you need it. In this case depending on you architechture you could use simple stateor the context API to reuse this data on several and nested components.
Other solution could involve using the localStorage, so you could store the data fetched on the localStorage and reuse this data on any component, you just will have to update the data when you need it.

VueJS realtime check disk

I am new in VueJS, i want to check disk realtime using VueJS but my code not working for realtime, needed to resfresh the page, I don't know why
here is my script :
var vo = new Vue({
el: '.data_env',
data () {
return {
data : {}
}
},
mounted () {
axios
.get(BASE_URL+'clients/get_disk_size')
.then(response => (
this.data = response.data
))
}
})
Anyone can help me out ?
You need to refresh the page because mounted() executed only during creation of the component.
If you have variable and want to fetch a new data when this variable changed, you can use watch or computed. If you want to get a new data whenever it changed on server side you need to use websocket.
According to Vue lifecycle,if you want to fetch result on realtime you should put you code inside computed and watch property.
If any changes occur it will do two way binding with Html element and show changes without refreshing page
For More info go through this link - https://v2.vuejs.org/v2/guide/computed.html

Categories

Resources