Console log inside React 'useEffect' function doesn't work after page refresh [duplicate] - javascript

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 1 year ago.
The 'useEffect' function is being used to retrieve data and then store it in the 'ratings' array. I'm currently trying to loop through the 'ratings' array elements in order to console log their contents. This works when the component is first mounted but stops working once the page is refreshed. I found that I can get it to work by placing the 'forEach' outside the useEffect function but was wondering why it doesn't work inside the function and if there's another solution.
const Rating = ({id}) => {
let url=`https://api.jikan.moe/v3/anime/${id}/stats`;
const [ratings, setRatings] = useState([]);
useEffect(() =>
{
(async function()
{
try{
const res = await axios.get(url);
setRatings(Object.values(res.data.scores));
if (ratings) ratings.forEach((rating)=>{console.log(rating.votes)}); //Doesn't work after refresh
}
catch(err)
{
console.log(err);
}
})();
}, [url])
...
}
export default Rating;

When you do setRatings(Object.values(res.data.scores));, the ratings state is not updated imediatelly, so if (ratings) is still the empty array when the app runs if (ratings) ....
Do something like this instead:
const scores = Object.values(res.data.scores);
setRatings(scores);
if (scores) scores.forEach((rating)=>{console.log(rating.votes)});
or use another useEffect for the ratings so it runs when it gets updated:
useEffect(() => {
if (ratings) ratings.forEach((rating)=>{console.log(rating.votes)});
}, [ratings]);

Related

Why does my react function function iterate twice?

I am currently trying out a project with the PokeAPI. And have used his guide for help. I can't get rid of the problem that the function iterates twice when called in the useEffect.
When I run the following code with the getAllPokemons in the useEffect
const PokeListPage = () => {
const [layoutToggle, setLayoutToggle] = useState(false);
const [allPokemons, setAllPokemons] = useState([]);
const [loadPoke, setLoadPoke] = useState(
"https://pokeapi.co/api/v2/pokemon?limit=20"
);
useEffect(() => {
getAllPokemons();
console.log(allPokemons);
}, []);
const getAllPokemons = async () => {
const res = await fetch(loadPoke);
const data = await res.json();
setLoadPoke(data.next);
function createPokemonObject(result) {
result.forEach(async (pokemon) => {
const res = await fetch(
`https://pokeapi.co/api/v2/pokemon/${pokemon.name}`
);
const data = await res.json();
setAllPokemons((currentList) => [...currentList, data]);
});
}
createPokemonObject(data.results);
console.log(allPokemons);
};
I get doublets of the first 20 objects in allPokemons. See output:
enter image description here
But when I remove the function and uses a button to trigger the function it behaves as expected. Which means that the function populates the allPokemon array with one object per pokemon. See output.
enter image description here
I have tried everything from copying entire files from other repositories and with an accuracy I didn't knew I had followed different tutorials but the problem remains. Does anyone know why?
It's bcz, you are rendering your app into a React. Strict mode component that runs specific functions and methods twice as a way to help you detect unintentional side effects. Since the side-effect is a state update, this triggers a rerender.
Use a useEffect to run the effect once when the component mounts.

Uncaught TypeError: Cannot read properties of undefined (reading 'question'). This is after using useState() to set the data from a GET request

I am making a simple GET request and want to make that data more accessible using useState() but it seems as though this error is caused by accessing an property that does not exist due to useState not updating it?
Even though I have made GET requests very similar to this, it is the first time I am using useLocation(). I'm not sure if that has anything to do with the problem or it has something to do with useState().
Any response is much appreciated
const getQuiz = async () => {
try{
// These values were passed by the difficulty Component
const categoryName = location.state?.name
const difficulty = location.state?.difficulty
// This makes a get request to get data for the quiz
let response = await axios.get(`https://the-trivia-api.com/api/questions?categories=${categoryName}&limit=10&difficulty=${difficulty}`)
let arrayDataResponse = await response.data
// This sets the data to question array so that it is accessible outside of this function
setQuestionArray(arrayDataResponse)
// this outputs an empty array
console.log(questionArray)
} catch(err){
console.log(err)
}
}
// This fetches the data on mount
useEffect(() => { getQuiz() }, [])
// This will set the data for the elements once the state of the question array has been set from the get request
useEffect(() => {
// This sets the content for the question element
setQuestion(questionArray[0].question)
// <h4>{question}</h4>
// Uncaught TypeError: Cannot read properties of undefined (reading 'question')
}, [questionArray])
I'm guessing that your state is defined something like this...
const [questionArray, setQuestionArray] = useState([]);
const [question, setQuestion] = useState(/* some initial value */);
This means that when your component is initialised and mounted, questionArray is an empty array.
Effect hooks not only execute when their dependencies change but also when they are initialised. That means when this hook first runs...
useEffect(() => {
setQuestion(questionArray[0].question);
}, [questionArray]);
It's trying to access .question on undefined, hence your error.
I would skip the question state and the above hook entirely. If you want something to represent the optional first question, you can use a memo hook instead
const firstQuestion = useMemo(() => questionArray[0]?.question, [questionArray]);
or simply use questionArray[0]?.question directly without any hooks.
This will either return the first question property or undefined which you can detect using conditional rendering
{firstQuestion && (
<p>{firstQuestion}</p>
)}
{/* or */}
{questionArray.length > 0 && (
<p>{questionArray[0].question}</p>
)}
const getQuiz = async () => {
try{
// These values were passed by the difficulty Component
const categoryName = location.state?.name
const difficulty = location.state?.difficulty
// This makes a get request to get data for the quiz
let response = await axios.get(`https://the-trivia-api.com/api/questions?categories=${categoryName}&limit=10&difficulty=${difficulty}`)
let arrayDataResponse = await response.data
// This sets the data to question array so that it is accessible outside of this function
setQuestionArray(arrayDataResponse)
//Solution
// set question from here
setQuestion(arrayDataResponse[0].question)
// this outputs an empty array
console.log(questionArray)
} catch(err){
console.log(err)
}
}
// then you don't need to run useEffect for this , Your state will be fiilled with api response
// not required code below
useEffect(() => {
// This sets the content for the question element
setQuestion(questionArray[0].question)
// <h4>{question}</h4>
// Uncaught TypeError: Cannot read properties of undefined (reading 'question')
}, [questionArray])

Get data using useeffect hook in react js [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 11 months ago.
I have a simple page editor, When a user clicks edit page it opens an editor. I am passing the ID of the page using redux which will be used to get data from API.
Here is my Editor.
const [pageData, setPageData] = useState("");
const getPage = async (id) => {
try {
const response = await api.get(`/landing_pages/${id}`);
console.log("page", response.data); // displays data at the end
setPageData(response.data);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getPage(pageID);
console.log('Page Data', pageData) // displays nothing
let LandingPage = pageData;
const editor = grapesjs.init({
container: "#editor",
components: LandingPage.components || LandingPage.html,
})
}, [pageID, getPage])
Why is Page Data display nothing even though the data from API is returned and is displayed in the console at the end? what am I doing wrong here?
Even if you await your getPage call, the updated pageData won't be available until the next render cycle so your assignment to LandingPage will be one cycle behind.
You should instead update in one useEffect and watch for changes to pageData in another.
const [pageData, setPageData] = useState("");
useEffect(() => {
const getPage = async (id) => {
try {
const response = await api.get(`/landing_pages/${id}`);
console.log("page", response.data); // displays data at the end
setPageData(response.data);
} catch (error) {
console.log(error);
}
};
getPage(pageID);
}, [pageID]);
useEffect(() => {
console.log('Page Data', pageData); // displays updated pageData
let LandingPage = pageData;
const editor = grapesjs.init({
container: "#editor",
components: LandingPage.components || LandingPage.html,
});
}, [pageData]);

How to render something that is async in React?

I'm making a react app that works with a API that provides data to my App. In my data base I have data about pins on a map. I want to show the info of those pins on my react app, I want them to render. I get that information with axios and this url: http://warm-hamlet-63390.herokuapp.com/pin/list
I want to retrieve the info from that url, with axios.get(url), stringify the JSON data and then parse it to an array of pins.
The Problem:
My page will be rendered before I get the data back from the server, because axios is async, so I will not be able to show anything. UseEffect and useState won't work because I need something in the first place (I think).
What i've tried:
I tried to use useEffect and useState, but as I said, I think I need something in the first place to change it after. I also tried to use await, but await won't stop the whole React App until it has a response, although it would be nice if there is something that stops the app and waits until I have the array with the info so I can show it on the App then. I tried everything with async. I'm fairly new to React so there might be something basic i'm mssing (?). I've been on this for days, I can't get this to work by any means.. Any help, youtube videos, documentation, examples, is help. Anything. How the hell do I render something that needs to wait for the server respond?
My code:
//function that stores the data in the result array,
//but result array will only be available after the
//server response, and after the page is rendered
async function pin(){
const result = []
var url = "http://warm-hamlet-63390.herokuapp.com/pin/list"
const res = await axios.get(url)
console.log(res.data.data);
if(res.data){
const txt = JSON.stringify(res.data.data)
const result = JSON.parse(txt)
console.log(result);
}
return result;
}
class App extends React.Component{
render(){
return(
<div>
<Pin/>
<Mapa/>
</div>
)
}
}
export default App
I don't fully understand what you are trying to output but how you would usually handle this is with both the useState hook and the useEffect hook see example below.
//function that stores the data in the result array,
//but result array will only be available after the
//server response, and after the page is rendered
const pin = () => {
const [result, setResults] = useState([]);
var url = "http://warm-hamlet-63390.herokuapp.com/pin/list"
useEffect(() => {
//Attempt to retreive data
try {
const res = transformData();
if (res) {
// Add any data transformation
setResults(transformData(res))
}
else {
throw (error)
}
}
catch (error) {
//Handle error
}
}, [])
// Handle data transformation
const transformData = async () => {
const res = await axios.get(url)
const txt = JSON.stringify(res.data.data)
const result = JSON.parse(txt)
return result
}
if (!result) {
// Return something until the data is loaded (usually a loader)
return null
}
// Return whatever you would like to return after response succeeded
return <></>;
}
This is all assuming that Pin is a component like you have shown in your code, alternatively, the call can be moved up to the parent component and you can add an inline check like below to render the pin and pass some data to it.
{result && <Pin property={someData} />}
Just a bit of background the useEffect hook has an empty dependency array shown at the end "[]" this means it will only run once, then once the data has updated the state this will cause a rerender and the change should be visible in your component
Rest assured, useEffect() will work. You need to use a condition to conditionally render the content when it comes back from the server.
In the example below if results has a length < 1 the message Loading ... will be rendered in the containing <div>, once you're results are received the state will be updated (triggering a re-render) and the condition in the template will be evaluated again. This time though results will have a length > 1 so results will be rendered instead of Loading ...
I’m operating under the assumption that you’re function pin() is returning the results array.
const app = (props) => {
const [results, setResult] = useState([]);
React.useEffect(() => {
const getPin = async () => {
if (!results) {
const results = await pin();
setResult([…results])
}
}
getPin();
},[results]);
return (
<div>
{result.length ? result : 'Loading ... '}
</div>
)
}

set state not working react hooks(string) asyncStorage [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 2 years ago.
hey all so im using react-natives-community async storage and i can't for the life of me get the state to save and im not too sure why. the first console.log from the await variable returns the correct information, but when i set the state the second console.log returns null and im not sure what's going on
const [userEmail, setUserEmail] = useState<string | null>(null);
const getEmail = await AsyncStorage.getItem('email')
console.log(getEmail + 'first')
setUserEmail(getEmail);
console.log(userEmail + 'second')
I made this custom hook but still no luck
const useGetAsyncStorage = (AsyncStorageItem: string): string => {
try {
const [data, setData] = useState<string | null>(null);
useEffect(() => {
const fetchAsyncStorage = async () => {
const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem);
console.log(AsyncStorageData)
setData(AsyncStorageData);
};
fetchAsyncStorage();
}, [AsyncStorageItem]);
return data as string
} catch (error) {
return error
}
};
The thing is state updates are asynchronous. You will end up seeing the null for the email what it was initially . If you want to see the change , you should do console.log in useEffect() hook

Categories

Resources