I'm learning Hooks with React and I'm trying to do a simple fetch to an API then I'm trying to save that data inside a Hook but It has not been possible for me.
import React, { useState, useEffect } from "react";
function useDogs() {
const [dogs, setDogs] = useState({
data: {}
});
useEffect(() => {
const fectData = async () => {
const data = await fetch("https://dog.ceo/api/breeds/image/random");
setDogs({ data: data.url });
console.log(data.url);
};
fectData();
}, []);
}
function Dogs() {
const dogs = useDogs();
console.log("dogs", dogs);
return <ul>{dogs} dogy</ul>;
}
export default Dogs;
In component Dogs() I'm having dogs as undefined
You aren't returning dogs from your useDogs hook.
(Also, to get at the response data, you need to await on .json() from the fetch response.)
import React, { useState, useEffect } from "react";
function useDogs() {
const [dogs, setDogs] = useState({
data: {},
});
useEffect(() => {
const getData = async () => {
const resp = await fetch("https://dog.ceo/api/breeds/image/random");
const data = await resp.json(); // <-- this
setDogs({ data });
console.log(resp, data);
};
getData();
}, []);
return dogs; // <-- this
}
function Dogs() {
const dogs = useDogs();
console.log("dogs", dogs);
return <ul>{dogs} dogy</ul>;
}
export default Dogs;
Custom Hooks are just javascript functions if you want to assign them to a variable you need to return something in your custom hook,
In some situations you need to set Something into your custom hook which you can do that by returning both value and setValue functions, for example in your case like below:
import React, { useState, useEffect } from "react";
function useDogs() {
const [dogs, setDogs] = useState({
data: {},
});
useEffect(() => {
const getData = async () => {
const resp = await fetch("https://dog.ceo/api/breeds/image/random");
const data = await resp.json(); // <-- this
setDogs({ data });
console.log(resp, data);
};
getData();
}, []);
return [dogs, setDogs]; // <-- this
}
and when you want to use it you just destructure it like this:
function Dogs() {
const [dogs, setDogs] = useDogs();
console.log("dogs", dogs);
return <ul>{dogs} dogy</ul>;
}
export default Dogs;
now you can read the data and also in future cases if you'ld like you can set the data too,
Related
why is fetchReviews not fetching?
Originally didn't use fetchData in use effect.
Ive tried using useDispatch.
BusinessId is being passed into the star component.
no errors in console.
please let me know if theres other files you need to see.
thank you!
star component:
import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import {AiFillStar } from "react-icons/ai";
import { fetchReviews } from '../../actions/review_actions';
function Star(props) {
const [rating, setRating] = useState(null);
// const [reviews, setReview] = useState(props.reviews)
// const dispatch = useDispatch();
useEffect(() => {
const fetchData = async () => {
await fetchReviews(props.businessId)
};
fetchData();
console.log(props);
// getAverageRating();
});
const getAverageRating = () => {
let totalStars = 0;
props.reviews.forEach(review => {totalStars += review.rating});
let averageStars = Math.ceil(totalStars / props.reviews.length);
setRating(averageStars);
}
return (
<div className='star-rating-container'>
{Array(5).fill().map((_, i) => {
const ratingValue = i + 1;
return (
<div className='each-star' key={ratingValue}>
<AiFillStar
className='star'
color={ratingValue <= rating ? '#D32322' : '#E4E5E9'}
size={24} />
</div>
)
})}
</div>
);
};
export default Star;
star_container:
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Star from "./star";
import { fetchReviews } from "../../actions/review_actions";
const mSTP = state => {
return {
reviews: Object.values(state.entities.reviews)
};
}
const mDTP = dispatch => {
return {
fetchReviews: businessId => dispatch(fetchReviews(businessId))
};
};
export default connect(mSTP, mDTP)(Star);
console image
why is fetchReviews not fetching? Originally didn't use fetchData in use effect. Ive tried using useDispatch. BusinessId is being passed into the star component. no errors in console.
edit!***
made some changes and added useDispatch. now it wont stop running. its constantly fetching.
function Star(props) {
const [rating, setRating] = useState(null);
const [reviews, setReview] = useState(null)
const dispatch = useDispatch();
useEffect(() => {
const fetchData = async () => {
const data = await dispatch(fetchReviews(props.businessId))
setReview(data);
};
fetchData();
// console.log(props);
// getAverageRating();
}), [];
ended up just calling using the ajax call in the useEffect.
useEffect(() => {
const fetchReviews = (businessId) =>
$.ajax({
method: "GET",
url: `/api/businesses/${businessId}/reviews`,
});
fetchReviews(props.businessId).then((reviews) => getAverageRating(reviews));
}), [];
if anyone knows how i can clean up and use the dispatch lmk.
ty all.
useEffect(() => {
const fetchData = async () => {
const data = await dispatch(fetchReviews(props.businessId))
setReview(data);
};
fetchData();
// console.log(props);
// getAverageRating();
}), [];
dependency array is outside the useEffect. Since useEffect has no dependency option passed, function inside useEffect will run in every render and in each render you keep dispatching action which changes the store which rerenders the component since it rerenders code inside useEffect runs
// pass the dependency array in correct place
useEffect(() => {
const fetchData = async () => {
const data = await dispatch(fetchReviews(props.businessId))
setReview(data);
};
fetchData();
// console.log(props);
// getAverageRating();
},[]), ;
Passing empty array [] means, code inside useEffect will run only once before your component mounted
I am relatively new to react hooks and I am trying to create this custom hook to handle CRUD operations for my API.
This is the hook file:
import React, { useState, useEffect } from "react";
const useApi = (url, headers = { method: "GET" }, payload = null) => {
const [isLoading, setIsLoading] = useState(true);
const [apiData, setApiData] = useState(null);
const [serverError, setServerError] = useState(null);
const [api, setApi] = useState({});
const list = async () => {
try {
const resp = await fetch(url);
const data = await resp?.json();
setApiData(data);
setIsLoading(false);
} catch (error) {
setServerError(error);
} finally {
setIsLoading(false);
}
};
const create = async () => {
try {
const resp = await fetch(url, (headers = { method: "POST" }), payload);
const data = await resp?.json();
setApiData(data);
setIsLoading(false);
} catch (error) {
setServerError(error);
} finally {
setIsLoading(false);
}
};
setApi({
...api,
list: list,
create: create
});
return { isLoading, apiData, serverError, api };
};
export default useApi;
However, when I call api.list() in my main component inside a useEffect() hook, I get an infinite loop.
Sample component call:
import { useEffect } from "react";
import useApi from "./useApi";
export default function App() {
const {
isLoading: loading,
apiData: students,
serverError: error,
api
} = useApi("https://59f0f160ce72350012bec011.mockapi.io/students");
console.log(loading, students, error, api);
useEffect(() => {
api.list();
}, [api]);
return (
<div className="App">
<h1>list</h1>
{loading ? "loading" : students.map((x) => x.name)}
</div>
);
}
Here's the sandbox for it:
https://codesandbox.io/s/cocky-chebyshev-d9q89?file=/src/App.js:0-492
Can anyone help me understand the issue?
Thank you in advance!
This is what is causing the infinite loop:
setApi({
...api,
list: list,
create: create
});
You are not supposed to call setState() during a render.
In your case, you don't need to useState for the api object, you can just return it on every render:
return {
isLoading,
apiData,
serverError,
api: { list, create }
};
Here is a link to the fixed sandbox
Also, another warning: this code will repeatedly call api.list().
useEffect(() => {
api.list();
}, [api]);
Since api changes on every render, it will repeatedly call api.list().
This is the object that changes on every render:
return { isLoading, apiData, serverError, api };
You can ensure that you only call api.list() one time by using a ref.
import { useRef } from 'react'
// In the component
const gotRef = useRef(false)
useEffect(() => {
if (!gotRef.current) {
api.list();
gotRef.current = true
}
}, [api]);
I am trying to import a function that fetches data from an api in a file (.src/api/index.js) to my App.js (.src/App.js).
.src/api/index.js
import axios from 'axios';
const url = 'https://covid19.mathdro.id/api';
export const fetchData = async () => {
try {
const res = await axios.get(url);
return res;
} catch (error) {}
};
.src/App.js
import React, { useEffect } from 'react';
import { fetchData } from './api';
const App = () => {
useEffect(() => {
const data = fetchData();
console.log(data);
}, []);
return <div></div>;
};
export default App;
};
I am getting a Promise{<pending>} in my console when I run this but I am trying to get the values in the object.
fetchData() is an async function, and you need to await it like so:
const data = await fetchData();
Then, the useEffect must also be an async function:
useEffect(async () => {
const data = await fetchData();
console.log(data);
}, []);
You are not waiting for promise to resolve. use await or .then. If you wanna use await, make callback function of useEffect async function.
const App = () => {
useEffect(async () => {
const data = await fetchData();
console.log(data);
}, []);
return <div></div>;
};
Other approach is to use .then.
const App = () => {
useEffect(async () => {
const data = fetchData().then((data) => console.log(data));
}, []);
return <div></div>;
};
Is there any reason a function in a react component would run multiple times although it is being invoked only once?
I have this test function that auto-invokes itself as in:
let xfunction = (() =>
{
console.log('test');
}
)();
This is what I get in the console:
App.js Source Code:
import React, { useState, useEffect } from 'react';
import { getAllPokemons } from './services/pokemon'
import './App.css';
function App() {
const [pokemonData, setPokemonData] = useState([]);
const [loading, setLoading] = useState(true);
const initialUrl = 'payload.json'
useEffect(() => {
async function fetchData() {
let response = await getAllPokemons(initialUrl);
console.log(response);
await loadingPokemon(response.pokemon);
setLoading(false);
}
fetchData();
}, [])
const loadingPokemon = async (data) => {
let _pokemon = await Promise.all(data.map(async pokemon => {
return pokemon;
})
);
setPokemonData(_pokemon);
}
// Start - Filter by Pokemon Type
let pokemonTypes = (() =>
{
console.log('test');
}
)();
// End - Filter by Pokemon Type
return (
<div></div>
);
}
export default App;
The function is not being called or references anywhere else!
Thanks!
Solution as proposed by #Jared Smith:
If you do not want your functions rerendered and you are using react hooks, please include them in the useEffect hook as in:
useEffect(() => {
async function fetchData() {
let response = await getAllPokemons(initialUrl);
await loadingPokemon(response.pokemon);
setLoading(false);
}
fetchData();
includeFunctionHere();
}, [])
I am fetching data from backend using axios whenever I am trying to update hooks it is not updating.
The data is JSON from where I am extracting data and trying to set element. It might sound silly but can somebody tell me what is dependent array?
I keep getting this
Line 18: React Hook useEffect has a missing dependency: 'elements'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Here is code
import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [elements, setElements] = useState([]);
useEffect(() => {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
console.log(data);
setElements(elements => [...elements, data]);
console.log(elements);
};
res();
}, []);
console.log(elements.map(element => console.log(element)));
return <div className='App'>Hello</div>;
}
export default App;
Just console.log outside your effect. You're already using the updater version of useState
setElements(elements => [...elements, data])
The missing dependecy warning is coming from console.log(elements)
import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [elements, setElements] = useState([]);
useEffect(() => {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
console.log(data);
setElements(elements => [...elements, data]);
};
res();
}, []);
console.log(elements);
return <div className='App'>Hello</div>;
}
export default App;
Missing dependency warning is because you use console.log(elements) inside the useEffect.
And your elements log is not showing latest result because state is not changed (yet)
Just add a useEffect to keep track of elements changes like below.
function App() {
const [elements, setElements] = useState([]);
useEffect(() => {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
console.log(data);
setElements(elements => [...elements, data]);
};
res();
}, []);
useEffect(() => console.log(elements), [elements])
return <div className='App'>Hello</div>;
}
export default App;
To answer your question;
The dependency array is their to let React know when the useEffect in this case should be triggered. So the useEffect i added, only triggers when its dependency elements is changed.
In your case you are puting the array data inside elements, setElements(elements => [...elements, data]); so it will be array inside array.
Try the below :
function App() {
const [elements, setElements] = useState([]);
useEffect(() => {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
console.log(data);
setElements([...elements, data]);
};
res();
}, []);
useEffect(() => console.log(elements), [elements])
return <div className='App'>Hello</div>;
}
export default App;