i'm studying hooks on reactjs with an api to request data, i would like to know if theres a way to request all pages at once and show the datas at the page. The api im using its from Rick and Morty API https://rickandmortyapi.com/api/character/ and you can see the result here https://project-soctest.herokuapp.com/
this is what i made so far using useEffect
useEffect(() => {
async function loadData() {
const apiResponse = await api.get(`?page=1`);
setCharacters(apiResponse.data.results);
}
loadData();
}, []);
No there is no way to get all the pages in this particular API.
Related
I have a page that displays data fetched from a MongoDb through API, in this page, you can modify the data and after that, the page will render again to display the new data. But inspecting the network requests I noticed my react app sends an infinite number of requests, which obviously slows down everything. I read this is caused by this snippet of code:
useEffect(() => {
fetchData();
}, [users]);
I also read I must empty the dependencies array of the useEffect, but If I do so, the page will not re-render if the data changes (for example after inserting a new record in the db).
This is the function I use to get the data from the db:
const [users, setUsers] = useState([]);
async function fetchData() {
const res = await fetch("http://localhost:8000/users/");
if (res.status === 401) {
console.log(res.json);
} else {
setUsers(await res.json());
}
}
How can I fix this? Thanks.
You created an infinite loop:
fetchData calls setUsers, which sets users. The effect reacts to changes to users, and calls fetchData again. ♾️
I don't know your exact use case, but one solution would be to only call fetchData when an actual user interaction has happend in your app that makes you want to fetch new data.
I have application with client-side on React and ReduxToolkit and server-side on NodeJS and Socket.io, with page of adding posts form and page for output posts, but I dont know how to dispatch posts to reduxtk store in every user
I'm trying on every adding of post, emit event to all users and they got this new post without additional fetch, and I did it, but I cant understand how to dispatch this new post to reduxtoolkit store in every user that are subscribed to this event, not only the one who added this post
useEffect(() => {
async function fetchPost(){
const posts = await postService.getPosts()
dispatch(setPosts(posts))
}
fetchPost()
socket.on("connect",()=>{
socket.send(`${user.userInfo.username} connected.`)
})
socket.on("updatePosts",async data=>{
const { createdPost } = data
dispatch(updatePosts(createdPost))
})
return () => {
socket.off("updatePosts")
}
}, [])
It seems nextjs getStaticProps is not working in components but working in pages. But I need to fetch api data to my components. Is there anyway to this?
I've tried this but I'm not happy with the process .
const [data, setData]=useState();
useEffect(()=>{
async function fetchData() {
const res = await fetch(
'https://domainname/api/vb1/category-tree'
);
const {data} = await res.json();
setData(data)
}
fetchData()
},[]);
If I understand correctly, you want to statically generate certain components using getStaticProps. In my opinion, the easiest way to do this would be to fetch the data you need in the page where your component is being used and pass the data as props to the component.
In my project I use ReactJS in combination with redux and firebase.
Creating a thunk to make async calls to firebase and store the data in redux.
When I'm fetching my files from firebase storage.
Using this method:
try {
let list = [];
await storage
.ref()
.child(path)
.listAll()
.then((res) => {
res.items.forEach((item) => {
storage
.ref()
.child(item.fullPath)
.getDownloadURL()
.then((urlRes) => {
list.push({
name: item.name,
url: urlRes,
});
});
});
});
dispatch(getFileActionSuccess(list));
This method works as intended.
It returns an array of files with their url to view/download them.
The problem is when I try to access this object in my state, it returns an empty array.
Even though when checking using Redux Devtools, I can clearly see that after the list was dispatched. And I could see the correct data.
Devtools image
Note: this is not the real code but a representation
function page() {
getFiles();
<filesList/>
}
function filesList() {
const files = useSelector((state) => state.files, _.isEqual);
console.log(files);
return (..insert render..);
}
But when logging the files. It shows an empty array at first. But when expanding it, it shows the correct data. But it doesn't render it. As I don't understand why it isn't showing like it is supposed to I no longer know what to do and how to fix this.
Simply fetch the data on component mount and component update, and update your state accordingly.
If you’re using React Hooks, you can use React.useState() and give it a dependency. In this case the dependency would be the part of your state which will update upon completion of your HTTP request.
I have build a simple pure react and meteor web app. I am trying to connect a flask API to my meteor.js app for the machine learning component of my application. I have seen examples for pure react front end but cant get the same logic to work for meteor.
what I did is:
make a flask app and return the prediction results to localhost:5000 as a python dictionary e.g.
{'class': 'bird', 'confidence':'0.8932'}
Set up a proxy in my meteor app in package.json, I have meteor app running at localhost:3000:
"proxy":"http://127.0.0.1:5000/"
finally, this is where I am confused, I have a bunch of components in my home page, I am not sure if I have to render the flask results in a component or page, nor how to do that. What I tried Is to render the results in one of the components using the useEffect, useState functions.
I get an error that says something like I can't use this funtionality.
function App() {
const [predictedClass, setPredictedClass] = useState(0);
useEffect(() => {
fetch('/prediction').then(res => res.json()).then(data => {
setPredictedClass(data.class);
});
}, []);
I use the useEffect method to get the data from the requests of my api.
example:
const [data, setData] = useState(null);
useEffect(() => {
getData('GET', '/api/test')
.then(response => {
setData(response)
})
.catch(error =>
console.log(error)
);
}, []);
Where getData is a custom function that calls an axios request.