React native Pull to refresh is not working - javascript

I m trying to add pull to refresh to fetch my data from my api but it is not working and i can'y find the problem within the code:
const[refresh,setRefresh]=useState(true)
const onRefresh=()=>{
try{
axios
.get('http://192.168.1.17:8000/File/')
.then((response)=> {
setFile(response.data);
setFilteredFile(response.data)
setEmpty(false)
setRefresh(false);
})}
catch(error){console.log(error)
}
}
useEffect(()=>{
onRefresh()
},[])
<FlatList style={DocumentStyle.flatstyle}
keyExtractor={(item)=>item['id']}
data={filteredfile}
renderItem={renderItem}
onRefresh={()=>onRefresh()}
refreshing={refresh}
/>

never mind me everyone, i haven't set my refresh back to true after the useEffect set it to false

The error is due to not importing useState, but you also need to import useEffect. I also dont see where some of the props your passing to FlatList are being used. But here's a working sample:
import {useState, useEffect} from 'react';
const FlatList = ({file, refreshing, onRefresh}) => {
return (
<div>
<p>{file}</p>
<button onClick={() => onRefresh(2)}>Load another todo</button>
</div>
)
}
export default function App() {
const [refresh, setRefresh] = useState(true);
const [file, setFile] = useState('');
useEffect(() => onRefresh(), []);
const onRefresh = (id=1) => {
try {
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(response => response.json())
.then(json => {
console.log(json)
setFile(JSON.stringify(json))
setRefresh(false);
})
}
catch(error) {
console.log(error);
}
}
return <FlatList file={file} refreshing={refresh} onRefresh={onRefresh} />
}

Related

Unable to display data from heroku api to the Dom

I am building an application using React Native, and I want to use data from Heroku api. But when I make an API call and consolog the data I can see the data, but when I try to map them, nothing is coming out of the DOM. Can anyone tell me what I am doing wrong? Thank you so much. Here below are my can and a screenshop.
App.jsx:
import react, { useEffect, useState } from "react";
import { FlatList, useWindowDimensions, View, Text } from "react-native";
import axios from "axios";
const App = () => {
const { height } = useWindowDimensions();
const [places, setPlaces] = useState({});
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
axios
.post(
"https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
)
.then((response) => console.log(response.data))
.catch((error) => setIsError(error))
.finally(() => setIsLoading(false));
}, []);
return (
<View>
{places.map(({ name, distance }) => (
<View>
<Text>name</Text>
<Text>{name}</Text>
<Text>{distance}</Text>
</View>
))}
</View>
);
};
export default App;
you are not updating the state here, only consoling the data,
useEffect(() => {
axios
.post(
"https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
)
.then((response) => setPlaces(response.data)) // here is the
//mistake
.catch((error) => setIsError(error))
.finally(() => setIsLoading(false));
}, []);
I've haven't worked with React Native but if it's the same as regular React, then the first problem I see is that each element inside your map should have a key:
{places.map(({ name, distance }) => (
<View key={name}>
{/* ... */}
</View>
))}
You also need to handle the loading state. Because when App first runs, places is undefined, so you are calling undefined.map which will probably throw an error. An early return would suffice.
if (!places) return <Text>Loading...</Text>
And I also don't see the setPlaces() being called, I assume you replaced it with the console log?

Error on fetch data, function instead of value

Hi guys I am trying to fetch data using get, and I want the data to be displayed after I click on the button, as a normal crud
I am new in programming if there is someone that can help me. I APPRECIATE THANKS
everything in my backend is ok, I try in postman and console.log is everything good. My problem is only in this part thanks
import { useState, useEffect } from "react";
import axios from "axios";
function Usuarios() {
const [users, setUsers] = useState([]);
useEffect(()=> {
const todosUsers = async () => {
const res= await axios.get("/users");
console.log(res)
setUsers(res.data);
}
todosUsers()
},[])
return (
<>
<button onClick=
{users.map((users) => (
<h1>{users.username}</h1>
))}></button>
</>
)
}
export default Usuarios;
one solution would be to keep a seperate variable to see if button is clicked as S.Singh mentioned
const [users, setUsers] = useState([]);
const [clicked, setClicked] = useState(false);
and in your component you can set the clicked variable to true on click
return (
<>
<button onClick={() => setClicked(true)}></button> //setting clicked true onclick
{clicked && users.map((users) => ( //only renders when click is true
<h1>{users.username}</h1>
))}
</>
)
if you want to hide and show alternatively on click just change the line to onClick={() => setClicked(!clicked)}
codesandbox demo
Move
{users.map((users) => (
<h1>{users.username}</h1>
))
}
from onClick definition and place it in an a markup where you want it to render. Define onClick hendler, which will be setting data from an API to a state
import { useState, useEffect } from "react";
import axios from "axios";
function Usuarios() {
const [users, setUsers] = useState([]);
const fetchOnClick = async () => {
await axios.get("/users");
console.log(res)
setUsers(res.data);
}
return (
<>
<button onClick={fetchOnClick}>
Fetch
</button>
<div>
{users.map((users) => (
<h1>{users.username}</h1>
))}
</div>
</>
)
}
OR
If you want to fetch the data inside useEffect hook, like you did in your example
import React, { useState, useEffect } from "react";
function Usuarios() {
const [users, setUsers] = useState([]);
const [isContainerShowed, setIsContainerShowed] = useState(false)
useEffect(() => {
const res= await axios.get("/users");
console.log(res)
setUsers(res.data);
}, [])
const displayContainer = () => setIsContainerShowed(true);
return (
<>
<button onClick={displayContainer}>
Fetch
</button>
<div style={{display: isContainerShowed ? "block" : "none"}}>
{users.map(users => <h1>{users.username}</h1>)}
</div>
</>
)
}
use Effect hook runs every time the component is rendered but as I understand, you want to display users when the button is clicked, so you can fetch users once the button is clicked and display them using the code below
import { useState, useEffect } from "react";
import axios from "axios";
function Usuarios() {
const [users, setUsers] = useState([]);
const fetchUsers= async () => {
const res= await axios.get("/users");
setUsers(res.data);
}
return (
<>
<button onClick={() => fetchUsers()}></button>
{
users.length && users.map(user => <h2>{user.username}</h2>)
}
</>
)
}

API giving data in second render in React

I was trying to fetch api with react.js but on first render its gives nothing and the second render its gives data. This makes it so when I try to access the data later for an image I get an error, TypeError: Cannot read property 'news.article' of undefined, because it is initially empty. how can I solve this?
here is my code ..
import React, { useEffect, useState } from 'react';
const HomeContent = () => {
const [news, updateNews] = useState([]);
console.log(news);
useEffect(() => {
const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
fetch(api)
.then(response => response.json())
.then(data => updateNews(data))
.catch((error) => console.log(error))
}, [])
return (
<>
</>
);
};
export default HomeContent;
There is no issue with the code itself, the output you receive is expected. However, you can render the content after it is retrieved as such
import React, { useEffect, useState } from 'react';
const HomeContent = () => {
const [news, updateNews] = useState([]);
const [isLoading, setIsLoading] = useState(true);
console.log(news);
useEffect(() => {
const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
fetch(api)
.then(response => response.json())
.then(data => {
updateNews(data.articles);
setIsLoading(false);
})
.catch((error) => {
console.log(error);
setIsLoading(false);
})
}, [])
return (
<>
{isLoading ?
<p>Loading...</p> :
// Some JSX rendering the data
}
</>
);
};
export default HomeContent;

fetching random json getting first undefined then result

Beginner on reactjs here, trying to fetch random json, getting the result i want to get, but not the way i want it, for some reason it prints first 'undefined' then after that the result. Why cant i get just the result and without this '?'
my code:
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setThumbnail(json);
});
}, []);
console.log(thumbnail[0]?.thumbnailUrl);
return (
<div className="App">
<h1>Build</h1>
<p></p>
</div>
);
}
export default App;
console.log() inside App() directly will use the initial state of. thumbnail which is the empty, so it will show undefined.
To check the thumbnail, you should use another useEffect with adding a thumbnail dependency.
useEffect(() => {
if (thumbnail.length > 0) {
console.log(thumbnail[0].thumbnailUrl);
}
}, [thumbnail]);
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
const [isLoaded, setLoaded] = useState(false);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setLoaded(true);
setThumbnail(json);
});
}, []);
useEffect(() => {
if (isLoaded) {
console.log(thumbnail[0]?.thumbnailUrl);
}
}, [thumbnail]);
return (
<div className="App">
<h1>Build</h1>
<p></p>
</div>
);
}
export default App;
While the response of your http does not come, you can simply render a loading component (a text in this example), then when thumbnail state changes, React will re-render your component and update it with the new data.
Just a working example:
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setThumbnail(json);
})
.finally(() => {
setIsLoading(false);
});
}, []);
return (
<div className="App">
<h1>Build</h1>
{isLoading ? (
<h3>Loading...</h3>
) : (
thumbnail.map((item) => {
return <span key={item.id}>{item.title}</span>;
})
)}
</div>
);
}
export default App;

Keep Getting a TypeError: guide.map is not a function

I can't seem to figure out why this is not working correctly. I have been looking it over for hours and I think I have it set up correctly but it keeps giving me the error. I am not sure if I have the state set incorrectly or not. When I console.log it its grabbing the sample data from the api and shows it in console.
import React, { useState, useEffect } from 'react'
import styled from 'styled-components'
import axios from 'axios'
import GuideData from './Guides/GuideData.js'
import GuideLoader from './Guides/GuideLoader.js'
const GuideRender= styled.div`
display:flex;
flex-direction:column;
justify-content:space-between;
border: 5px black;
`
const HomePage = () => {
const[guide, setGuide]=useState([]);
const apiLink ='https://how-to-guide-unit4-build.herokuapp.com/api/guides/'
useEffect(() => {
axios
.get(apiLink)
.then(response => setGuide(response))
.catch(err =>
console.log(err));
}, []);
console.log(guide)
if (!guide) return <GuideLoader />;
return (
<div>
<GuideRender>
{guide.map(item => (
<GuideData key={item} item={item} />
))}
</GuideRender>
<div>
<button>Create Article</button>
</div>
</div>
)
}
export default HomePage
Here you go, cleaned up your useEffect function a bit. The error was that you were setting just the response, and not response.data.
const HomePage = () => {
const [guide, setGuide] = useState([]);
const [loading, setLoading] = useState(true);
const apiLink = "https://how-to-guide-unit4-build.herokuapp.com/api/guides/";
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await axios.get(apiLink);
setGuide(response.data);
setLoading(false);
} catch (error) {
console.log(error);
}
};
if (loading) {
return "Loading...";
}
console.log(guide);
return (
<div>
<GuideRender>
{guide.map(item => (
<GuideData key={item} item={item} />
))}
</GuideRender>
<div>
<button>Create Article</button>
</div>
</div>
);
};
Your code seems fine. You can use optional chaining to avoid components breaking while API intergration. Working sandbox

Categories

Resources